Yehoshaphat Schellekens Yehoshaphat Schellekens - 5 months ago 14
Bash Question

system commant wont work as in shell when calling a python comman on Ubuntu from R

I'm trying to invoke within

R
a system command that invokes a call to a python script (that includes an import to pandas) as following:

getwd()
[1] "/home/production"
> system("python In_tag_main_model/python_scripts/connect_to_couchbase.py")
Traceback (most recent call last):
File "In_tag_main_model/python_scripts/connect_to_couchbase.py", line 11, in <module>
import pandas as pd
ImportError: No module named pandas


Within
connect_to_couchbase.py
i'm calling pandas, which isn't recognized, though when i'm running this exact command from my machines shell:

production@va-rsrv01:~$ python In_tag_main_model/python_scripts/connect_to_couchbase.py
production@va-rsrv01:~$


It works great,any ides why
system
isn't working for me?

Thanks in advance!

Answer

It looks like the R system function is executing a different python executable. You have three options to specify which executable you want:

  • You the absolute path:

    system("/anaconda2/bin/python In_tag_main_model/python_scripts/connect_to_couchbase.py")
    
  • Set the PATH variable for your process via Sys.setenv (as you have done):

    Sys.setenv(PATH="/anaconda2/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bi‌​n:/sbin:/bin:/usr/games")
    system("python In_tag_main_model/python_scripts/connect_to_couchbase.py") 
    
  • Use the newer system2 function which provides an env argument that can be used to modify the environmental variables for the subprocess:

    system2("python",
            args="In_tag_main_model/python_scripts/connect_to_couchbase.py",
            env="PATH=/anaconda2/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bi‌​n:/sbin:/bin:/usr/games")
    

    Note that system2 has a different calling convention than system.