For context: My goal is to create a graphic interface so that the user can run a program that I have been developing in R. The interface is done using the Tkinter module from python (version 3.3). Right now I am trying to make it work in Windows.
I believe I have successfully called the R interpreter using python to run my R file (run.R). In this file I call the R package 'seqinr'. However when I call the R interpreter from python I obtain this:
I run this:
os.system('C:/"Program Files"/R/R-3.6.1/bin/Rscript run.R')
and I obtain this:
Error in library(seqinr) : there is no package called 'seqinr'
Calls: source -> withVisible -> eval -> eval -> library
Execution halted
However, when I run the 'C:/"Program Files"/R/R-3.6.1/bin/Rscript run.R' command in the Command Prompt, it works perfectly and I have no problems.
I also checked where my package is installed and it's in the default directory that R uses to install all the packages. I also do not have any other R versions installed in my machine.
I have no clue what is happening now, so I would appreciate any help.
Thank you!
Although probably not satisfactory, I'd recommend changing your "run.R" file to include the following lines:
if (!("seqinr" %in% installed.packages())) {
install.packages('seqinr', repos = "https://cloud.r-project.org")
}
library(seqinr)
This will install the package if it isn't available to wherever R is looking for packages when being called from Python. Additionally, you could include print(rownames(installed.packages())) in your "run.R" file to see what packages are currently available to your R installation at run time when calling from Python. Inclusion of the line print(.libPaths()) will tell you where R is looking for installed packages at run time as well.
Related
I am new to Julia. I developed a few lines of code to get the results I needed from packages I was not able to find in Python or R. Now, I am trying to get this file to be easily accessible, and wrap the code in Python or R. Has anyone done this before? I have tried a few methods and have not found anything that has helped.
The most simple way to do this would be just a few lines of code that calls the .jl file, runs it (which the code is then added to a .txt file from julia), and then alerts you when the code is done.
Any help would be greatly appreciated. R is the preferable method and at this point Python would be appreciated as well.
Please find below instructions for Python, R and just an external process (which of course is an executable command that can be run from any other process). I recommend putting your code in a package and loading it in one of those languages rather than executing this as an external process.
Python
Use Python Anaconda (not in-built system Python) and install Julia
Run Julia and install PyCall
using Pkg
ENV["PYTHON"]="/path/to/your/python/executable"
pkg"add PyCall"
pkg"build PyCall"
Put your code into a Julia package
using Pkg
Pkg.generate("MyPackage")
In the folder src you will find MyPackage.jl, edit it to look like this:
module MyPackage
function main(x,y)
#do very complex staff or place it in your_other_file.jl
2x.+y
end
include("your_other_file.jl")
export main, and_whatever_other_functio_you_defined
end
Install pyjulia
python -m pip install julia
(On Linux systems you might want to use python3 instead of python command)
For this step note that while an external Python can be used with Julia. However, for a convenience it might be worth
to consider using a Python that got installed together with Julia as PyCall.
In that case for installation use a command such this one:
%HOMEPATH%\.julia\conda\3\python -m pip install julia
or on Linux
~/.julia/conda/3/python -m pip install julia
Note that if you have JULIA_DEPOT_PATH variable defined you can replace %HOMEPATH%\.julia or ~/.julia/ with its value.
Run the appropiate Python and tell it to configure the Python-Julia integration:
import julia
julia.install()
Now you are ready to call your Julia code:
>>> from julia import Pkg
>>> Pkg.activate(".\\MyPackage") #use the correct path
Activating environment at `MyPackage\Project.toml`
>>> from julia import MyPackage
>>> MyPackage.main([1,2],5)
[7,9]
Gnu R
Configure your system PATH variable to point to your Julia location. Hence when you type julia in the console it should start Julia
Run the script below to install R-Julia integration
install.packages("JuliaCall")
library(JuliaCall)
julia <- julia_setup()
Follow the above instructions for Python (step 3 only) and create the package named MyPackage
Run the code
library(JuliaCall)
julia_eval("using Pkg;Pkg.activate(\"C:/temp/rrr/MyPackage\")")
julia_library("MyPackage")
julia_eval("MyPackage.main(3,5)")
Bash (or just any language)
Build the package following instructions for Python (step 3 only)
Configure the system PATH variable
Being in the package directory run the command (note string(:.) is a Julian trick that I use to avoid apostrophe escaping in bash commands):
julia -e "using Pkg;Pkg.activate(string(:.));Pkg.instantiate();using MyPackage;MyPackage.main(3,4)"
This will install all dependencies for your package. In order to skip the installation remove Pkg.instantiate() from the above command.
The answer from #przemyslaw-szufel is correct but maybe a bit overcomplicated. You don't necessarily need to wrap your code in a module or define a custom environment (yes it is good practice, but a step at the time...)
First create a file juliaScripts.jl with content:
function getAnElement(array,n)
return array[n]
end
To run functions defined in a .jl file in R
Then in R you just do:
> install.packages("JuliaCall")
> library(JuliaCall)
> julia_setup() # on every new R session !
> julia_source("juliaScript.jl")
> out <- julia_call("getAnElement",c(10,20,30),2)
> out
[1] 20
Note that the R vector has been automatically converted to a Julia Array.
To run functions defined in a .jl file in Python
In Python, it is even easier:
$ python3 -m pip install --user julia
>>> import julia
>>> julia.install() # only once, not every session
>>> jl=julia.Julia(compiled_modules=False)
>>> from julia import Main
>>> Main.include("juliaScript.jl")
>>> Main.getAnElement([1,2,3],2)
20
Also in Python arrays (native python lists as well Numpy arrays and other commonly used data structures) are automatically converted between Python and Julia.
Not to make advertising, but more details on interfacing R <-> Julia or Python <-> Julia are on my Apress(2019) book "Julia Quick Syntax reference" in Chapter 7 "Interfacing Julia with other languages" (I shouldn't say it, but you can easily find the pdf online in well-known sites...)
Using the JuliaConnectoR package:
library(JuliaConnectoR)
fun <- juliaCall("include", "/path/to/file.jl") # you may need to provide the full path
For more info on JuliaConnectoR, see the link above as well as this paper, which additionally compares it to alternative packages suck as JuliaCall and XRJulia.
I want to read a python file in R and I am using reticulate package for that.
I have certain packages in python file. Do I have to install them in R env again somehow, for the file to run? And how do I do that?
I am getting this error:
Error in py_run_file_impl(file, local, convert) :
ModuleNotFoundError: No module named 'descartes'
How do I fix this?
What worked for me was first installing the python customLibrary via the python command line interface.
Second, in my R project folder I specified the python function in a file customLibrary.py which specifies import as first line, such as:
import customLibrary as CL
def custoFunction(path):
A = CL.test(path)
return(A)
Third, I call the function from R via standard reticulate::source_python("customLibrary.py") implementation (You may need to check whether your directory-path is correct via R command getwd().)
It may be helpful to start with small steps to narrow down the issue:
just write a simple function, such as "addThree" that is essentially y = x + 3 etc.
try to execute it in python
try to execute if from R
If both works you can try to do the same thing with the custom library.
I am a big fan of Rstudio Cloud and would like to inter-grate R and Python by using the package Reticulate.
It looks like Rstudio Cloud is using python 2.7 (no problems with that). When I try to write Python Code in an R markdown document, nothing gets run.
---
title: "reticulate"
output: html_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r}
library(reticulate)
py_config()
```
```{python}
import pandas
x = 4
```
Python code does not get run.
I am also finding that if I want to install python packages in an R script using reticulate. I have to create a virtual environment. What is the reason behind that?
library(reticulate)
virtualenv_create("r-reticulate")
virtualenv_install("r-reticulate", "scipy")
virtualenv_install("r-reticulate", "pandas")
If I use conda_install, I get an error message.
conda_create("r-reticulate")
Error: Unable to find conda binary. Is Anaconda installed?
conda_install("r-reticulate", "scipy")
Error: Unable to find conda binary. Is Anaconda installed?
The goal is to have python working in Rstudio cloud on R markdown. I can not install packages and execute code.
I just succeeded in getting Conda installed in Rstudio cloud after receiving the same error message as you1, so thought I'd share how I got this working.
I created two scripts:
to install miniconda (i think that's the step you're missing, and why Conda didn't work for you) and then restartSession for this to be accessible
to seperately store the commands for setting up Conda, with the running of this script passed as a command to the call to restartSession (because otherwise the commands are triggered before R has restarted, and they fail; sys.sleep() didn't seem to work, but this method did)
setup.R
setwd("/cloud/project") # to ensure students get required resources
install.packages("rstudioapi") # to restart R session w/ installations
install.packages("reticulate") # for python
reticulate::install_miniconda("miniconda") # for python
# Restart again to make sure all system things are loaded
# and then create a new Conda environment
rstudioapi::restartSession(command="source('nested_reticulate_setup.R')")
nested_reticulate_setup.R
reticulate::conda_create("r-reticulate")
reticulate::conda_install("r-reticulate", "scipy")
Sys.setenv(RETICULATE_PYTHON="/cloud/project/miniconda/envs/r-reticulate/bin/python")
reticulate::use_condaenv("r-reticulate")
osmnx <- reticulate::import("scipy")
Then if you make a call to scipy, eg scicpy$`__version__` , I believe it should work for you without that error you observed.
I couldn't find a solution to this issue elsewhere, so thought it worth responding to this old post in case it helps somebody some day. I am sure there are other ways of approaching this.
1 Perhaps for a different reason; i'll explain later in the post...
Just working my way through a (very good) book call Test Driven Development using Python.
This makes use of Python3.4 by the way. By the way, I am running in a Windows 7 OS.
I've got all the stuff working using a simple text editor and running from the command line... in the course of which in particular I used "pip install" to install Django and Selenium, as per book's instructions.
This created folders "selenium" and "django" under ...\Python34\Lib\site-packages\ ... so I added these to the PythonPath for my Eclipse/PyDev project.
With the correct interpreter selected I then tried to run a file which runs fine on the command line: "> python3 functional_tests.py"... but I get
File "D:\apps\Python34\lib\site-packages\django\http\__init__.py", line 1, in <module>
from django.http.cookie import SimpleCookie, parse_cookie
File "D:\apps\Python34\lib\site-packages\django\http\cookie.py", line 5, in <module>
from django.utils.six.moves import http_cookies
ImportError: cannot import name 'http_cookies'
... to me this looks like a dependency thing... as though "pip install" handles dependency matters in a way just including a single folder doesn't.
Question boils down to this: what's the "proper" way to install a python module using PyDev?
several days later
wow... nothing? Nothing! I suppose this must mean that you either have to add dependencies manually or use something like Ant, Maven or Gradle within Eclipse itself. These latter are not my strong areas, even outside an IDE. Would still be nice to have an answer from a PyDev expert!
Well, pip install should work for PyDev (it should automatically recognize the dependency)...
I.e.: in your use case, the only folder that should be in the PYTHONPATH is D:\apps\Python34\lib\site-packages (and pip should install packages to that folder -- make sure you don't add extra folders for "D:\apps\Python34\lib\site-packages\django" nor anything else inside the site-packages to the PYTHONPATH).
If it's still not working, please check if the module django.utils.six.moves.http_cookies is indeed where you expect it to be. Also, you can print the PYTHONPATH being used in runtime with:
import sys
print('\n'.join(sorted(sys.path)))
To check if that's really what you expect.
I'm writing a simple IronWorker in Python to do some work with the AWS API.
To do so I want to use the boto library which is distributed via PyPi repository. The boto library is not installed by default in the IronWorker runtime environment.
How can I bundle the boto library dependancy with my IronWorker code?
Ideally I'm hoping I can use something like the gem dependancy bundling available for Ruby IronWorkers - i.e in myRuby.worker specify
gemfile '../Gemfile', 'common', 'worker' # merges gems from common and worker groups
In the Python Loggly sample, I see that the hoover library is used:
#here we have to include hoover library with worker.
hoover_dir = os.path.dirname(hoover.__file__)
shutil.copytree(hoover_dir, worker_dir + '/loggly') #copy it to worker directory
However, I can't see where/how you specify which hoover library version you want, or where to download it from.
What is the official/correct way to use 3rd party libraries in Python IronWorkers?
Newer iron_worker version has native support of pip command.
So, you need:
runtime "python"
exec "something.py"
pip "boto"
pip "someotherpip"
full_remote_build true
[edit]We've worked on our toolset a bit since this answer was written and accepted. The answer from my colleague below is the recommended course moving forward.[/edit]
I wrote the Python client library for IronWorker. I'm also employed by Iron.io.
If you're using the Python client library, the easiest (and recommended) way to do this is to just copy over the library's installed folder, and include it when uploading the package. That's what the Python Loggly sample is doing above. As you said, that doesn't specify a version or where to download the library from, because it doesn't care. It just takes the one installed on your system and uses it. Whatever you get when you enter "import boto" on your local machine is what would be uploaded.
The other option is using our CLI to upload your worker, with a .worker file.
To do this, here's what you'd need to do:
Create a botoworker.worker file:
runtime "binary"
build 'pip install --install-option="--prefix=`pwd`/pips" boto'
file 'botoworker.py'
exec "botoworker.sh"
That second line is the pip command that will be run to install the dependency. You can modify it like you would any pip command run from the command line. It's going to execute that command on the worker during the "build" phase, so it's only executed once instead of every time you run a task.
The third line should be changed to the Python file you want to run--it's your Python worker file. Here's the one we used to test this:
import boto
If you save that as botoworker.py, the above should work without any modification. :)
The fourth line is a shell script that's going to actually run your worker. I've included the one we used below. Just save it as botoworker.sh, and you won't have to worry about modifying the .worker file above.
PYTHONPATH="$HOME/pips/lib/python2.7/site-packages:$PYTHONPATH" python botoworker.py "$#"
You'll notice it refers to your Python file--if you don't name your Python file botoworker.py, remember to change it here, too. All this does is set your PYTHONPATH to include the installed library, and then runs your Python file.
To upload this, just make sure you have the CLI installed (gem install iron_worker_ng, making sure your Ruby version is 1.9.3 or higher) and then run "iron_worker upload botoworker" in your shell, from the same directory your botoworker.worker file is in.
Hope this helps!