将 python 子进程与模块加载一起使用
Using python subprocess with module load
我目前在 unix 环境中使用 Python 2.7。
我需要在我的 python 脚本中使用 运行 R 脚本,但我无法让它工作,因为我的 R 模块需要先加载(使用 "module load")
这是我的 python 脚本:
import os
import subprocess as sp
os.system('module load R/3.2.3')
out = sp.check_output(['Rscript','test.R'], universal_newlines=True)
我一直遇到同样的错误:“[Errno 2] 没有那个文件或目录”
有什么想法吗?
我查看了 here and here 但无法正常工作。
感谢您的帮助!
所以 "module load" 实际上做的是在调用 shell 时设置一些环境变量。所以当你这样做时:
os.system('module load R/3.2.3')
Python 创建一个进程,运行s /bin/sh
在其中,并将该命令传递给 shell。模块环境变量设置在 shell 中。然后 shell 退出——工作完成!
环境变量不会——也不能——传播回 Python 进程。所以当你这样做时:
sp.check_output(['Rscript','test.R'])
你之前运行module load
完全不相干
那你怎么解决这个问题呢?好吧,一种可能性是明确指定 Rscript
:
的路径
sp.check_output(['/your/full/path/to/Rscript','test.R'])
另一种方法是组合您的命令:
sp.check_output('module load R/3.2.3 && Rscript test.R', shell=True)
最后,您可以简单地 运行 module load
在 运行 开始您的 Python 脚本之前。它设置的环境变量可以一直传播到 Python.
内的 R 调用
顺便说一下,可以直接从 Python 调用 R:http://rpy.sourceforge.net/rpy2/doc-dev/html/introduction.html
我目前在 unix 环境中使用 Python 2.7。 我需要在我的 python 脚本中使用 运行 R 脚本,但我无法让它工作,因为我的 R 模块需要先加载(使用 "module load")
这是我的 python 脚本:
import os
import subprocess as sp
os.system('module load R/3.2.3')
out = sp.check_output(['Rscript','test.R'], universal_newlines=True)
我一直遇到同样的错误:“[Errno 2] 没有那个文件或目录”
有什么想法吗? 我查看了 here and here 但无法正常工作。
感谢您的帮助!
所以 "module load" 实际上做的是在调用 shell 时设置一些环境变量。所以当你这样做时:
os.system('module load R/3.2.3')
Python 创建一个进程,运行s /bin/sh
在其中,并将该命令传递给 shell。模块环境变量设置在 shell 中。然后 shell 退出——工作完成!
环境变量不会——也不能——传播回 Python 进程。所以当你这样做时:
sp.check_output(['Rscript','test.R'])
你之前运行module load
完全不相干
那你怎么解决这个问题呢?好吧,一种可能性是明确指定 Rscript
:
sp.check_output(['/your/full/path/to/Rscript','test.R'])
另一种方法是组合您的命令:
sp.check_output('module load R/3.2.3 && Rscript test.R', shell=True)
最后,您可以简单地 运行 module load
在 运行 开始您的 Python 脚本之前。它设置的环境变量可以一直传播到 Python.
顺便说一下,可以直接从 Python 调用 R:http://rpy.sourceforge.net/rpy2/doc-dev/html/introduction.html