I have a pretty simple python script (Test.py
) in my "C:\Apache24\htdocs\Test\cgi-bin"
folder which contains the following code:
#!/Python/python
print("Content-type: text/html")
print()
import os
os.environ['R_HOME'] = 'C:\Program Files\R\R-3.4.1'
os.environ['R_USER'] = 'C:\Python\Lib\site-packages\rpy2'
# importing rpy2
import rpy2.robjects as robjects
# test : evaluating R code
robjects.r('''
# create a function `f`
f <- function(r, verbose=FALSE) {
if (verbose) {
cat("I am calling f().\n")
}
2 * pi * r
}
''')
r_f = robjects.r['f']
res = r_f(3)
print(res[0])
Now when executing it in a python shell it works just fine. However, calling the script from a web request (even localhost) just loads the page indefinitely.
I'm working on a Windows Server 2008 R2 x64 OS via RemoteDesktopConnection
Python 3.6: "C:\Python" + rpy2 version: 2.8.6
R 3.4.1: "C:\Program Files\R\R-3.4.1"
Apache: "C:\Apache24"
import os
and os.environ['...
commands I have set up according to this post because I was not able to set it up with global system variables.
However I have the environment variables set (I am able to launch R in cmd.exe), but my rpy2 won't work (even in a python shell) without the above commands.
Path: "...;C:\Python\Scripts\;C:\Python\;C:\Program Files\R\R-3.4.1\bin\x64"
R_HOME: "C:\Program Files\R\R-3.4.1"
R_USER: "C:\Python\Lib\site-packages\rpy2"
I know my apache server can execute python scripts as cgi (I have other python scripts which execute just fine via web request). It is really just the import rpy2.robjects command which makes the trouble
Any help would be much appreciated!
Apparently it was the most obvious/stupid thing that happened. In my python script using forward slash instead of backslash did solve my issue. So my updated code looks as follows:
#!/Python/python
print("Content-type: text/html")
print()
import os
os.environ['PYTHONHOME'] = 'C:/Python'
os.environ['PYTHONPATH'] = 'C:/Python/lib/site-packages'
os.environ['R_HOME'] = 'C:/Program Files/R/R-3.4.1'
os.environ['R_USER'] = 'C:/Python/Lib/site-packages/rpy2'
# importing rpy2
import rpy2.robjects as robjects
# test : evaluating R code
robjects.r('''
# create a function `f`
f <- function(r, verbose=FALSE) {
if (verbose) {
cat("I am calling f().\n")
}
2 * pi * r
}
''')
r_f = robjects.r['f']
res = r_f(3)
print(res[0])
This script executed the way it is supposed to when being called via a web request.