0

I'm trying to use R to run a Python script. I'm creating an R script that calls my Python script. I need to do this from the command prompt and pass along 3 arguments (latitude, longitude, and year) in integer form. Below is my R script:

args <- commandArgs(trailingOnly = TRUE)
lat_desired = args[1]
lon_desired = args[2]
year_desired = args[3]
system('/home/ "import sys; sys.stdout.write(file(\'python_file\', \'r\').read());"; python python_file lat_desired, lon_desired, year_desired')

My python script reads the lat_desired/lon_desired/year_desired arguments and converts them to integers (shown below):

line4 > lat_desired = int(sys.argv[1])
line5 > lon_desired = int(sys.argv[2])
line6 > year_desired = int(sys.argv[3])

When I run all of this in the command prompt I get this: Error: invalid literal for int() with base 10. Any ideas on how to pass along command line arguments from my R script to my Python script?

2
  • Perhaps you should print sys.argv from your python script to see what it's getting. Commented Dec 3, 2015 at 21:29
  • Maybe try running things from a batch file and call the commands there. Maybe have the R script write a csv that python will open. I've used this method to link several programs for modeling purposes. Commented Dec 3, 2015 at 21:54

1 Answer 1

2

In system() you're passing the strings "lat_desired", "lon_desired", and "year_desired". You need to do a little bit of text processing before passing all of this into system(). You can also make it a little bit more compact.

args <- commandArgs(trailingOnly = TRUE)
command <- sprintf(
    '/home/ "import sys; sys.stdout.write(file(\'python_file\', \'r\').read());"; python python_file %s, %s, %s',
    args[1], args[2], args[3])
system(command)

Also, you could just convert these to integers in R if you're going to be continuing to work with them in R.

args <- as.integer(commandArgs(trailingOnly = TRUE))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.