在R中使用system()调用python来运行模拟python控制台的python脚本

Yih*_*Xie 11 python r

我想用R之类的东西将一大块Python代码传递给Python system('python ...'),我想知道在这种情况下是否有一种简单的方法来模拟python控制台.例如,假设代码是"print 'hello world'",我怎样才能在R中获得这样的输出?

>>> print 'hello world'
hello world
Run Code Online (Sandbox Code Playgroud)

这只显示输出:

> system("python -c 'print \"hello world\"'")
hello world
Run Code Online (Sandbox Code Playgroud)

谢谢!

顺便说一句,我在r-help中问过但还没有得到回复(如果我这样做,我会在这里发布答案).

Cal*_*eng 11

你的意思是这样的吗?

export NUM=10
R -q -e "rnorm($NUM)"
Run Code Online (Sandbox Code Playgroud)

您可能还想查看littler- http://dirk.eddelbuettel.com/code/littler.html

更新

根据您的评论,我认为我开始更好地理解您的问题.你问的是在R shell中运行python.

所以这是一个例子: -

# code in a file named myfirstpythonfile.py

a = 1 
b = 19
c = 3 
mylist = [a, b, c]
for item in mylist:
    print item
Run Code Online (Sandbox Code Playgroud)

因此,在你的R shell中,执行以下操作:

> system('python myfirstpythonfile.py')
1
19
3
Run Code Online (Sandbox Code Playgroud)

基本上,您可以简单地调用python /path/to/your/python/file.py执行一段python代码.

在我的情况下,我可以简单地调用python myfirstpythonfile.py假设我在我的python文件所在的同一目录(路径)中启动了我的R shell.

进一步更新

如果你真的想要打印出源代码,这里有一种可能的强力方法.在你的R shell: -

> system('python -c "import sys; sys.stdout.write(file(\'myfirstpythonfile.py\', \'r\').read());"; python myfirstpythonfile.py')
a = 1
b = 19
c = 3
mylist = [a, b, c]
for item in mylist:
    print item
1
19
3
Run Code Online (Sandbox Code Playgroud)

并进一步更新:-)

因此,如果目的是在执行代码之前打印python代码,我们可以使用python跟踪模块(参考:http://docs.python.org/library/trace.html).在命令行中,我们使用-m选项来调用python模块,然后为它后面的python模块指定选项.

所以对于我上面的例子,它将是: -

$ python -m trace --trace myfirstpythonfile.py
 --- modulename: myfirstpythonfile, funcname: <module>
myfirstpythonfile.py(1): a = 1
myfirstpythonfile.py(2): b = 19
myfirstpythonfile.py(3): c = 3
myfirstpythonfile.py(4): mylist = [a, b, c]
myfirstpythonfile.py(5): for item in mylist:
myfirstpythonfile.py(6):     print item
1
myfirstpythonfile.py(5): for item in mylist:
myfirstpythonfile.py(6):     print item
19
myfirstpythonfile.py(5): for item in mylist:
myfirstpythonfile.py(6):     print item
3
myfirstpythonfile.py(5): for item in mylist:
 --- modulename: trace, funcname: _unsettrace
trace.py(80):         sys.settrace(None)
Run Code Online (Sandbox Code Playgroud)

我们可以看到,跟踪python代码的确切行,紧接着执行结果并将其输出到stdout.