简体   繁体   English

具有多个Python命令的R系统调用

[英]R System Call with Multiple Python Commands

I need to pass multiple python commands into one system call (in R), and I am having difficulty with the syntax. 我需要将多个python命令传递给一个系统调用(在R中),并且语法有困难。

What I'm trying to combine: 我想结合的是:

system("python "file1.py" -f "module_to_load1.py" -o "output_loc_file1"")
system("python "file2.py" -f "module_to_load2.py" -o "output_loc_file2"")

Simplified code: 简化代码:

 pystr="python -c print('hi')"
 system(paste(pystr, " && ", pystr, sep=""))

My desired output is: 我想要的输出是:

hi
hi

If I enter the code directly into the command prompt, I get the desired output: 如果直接在命令提示符下输入代码,则会得到所需的输出:

python -c print('hi') && python -c print('hi')

>> hi
>> hi

However, the system call is only returning a single 'hi', and I can't figure out what my dumb error is. 但是,系统调用仅返回一个“ hi”,我无法弄清楚我的愚蠢错误是什么。 Any help would be much appreciated. 任何帮助将非常感激。

You're better off storing it as a script than trying to manage a messy system call: 您最好将其存储为脚本,而不是尝试管理混乱的系统调用:

file: my.py 文件:my.py

print "hi"
print "hi"

Then from R: 然后从R:

> system("python my.py")
hi
hi

In the case that your actual code is much more complicated, you can generate python code and write it to a file that you then call. 如果您的实际代码复杂得多,则可以生成python代码并将其写入到您随后调用的文件中。

You can't just line up quotes like that -- embedded quotes need to be escaped. 您不能只像这样排列引号-需要转义嵌入式引号。 So instead of 所以代替

system("python "file1.py" -f "module_to_load1.py" -o "output_loc_file1"")

do

system("python \"file1.py\" -f \"module_to_load1.py\" -o \"output_loc_file1\"")

or simply omit the quotes as the filenames do not contain troublesome characters: 或直接省略引号,因为文件名不包含麻烦的字符:

system("python file1.py -f module_to_load1.py -o output_loc_file1")

The recommendation about writing proper Python scripts is still a good one. 关于编写适当的Python脚本的建议仍然是一个不错的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM