我知道有一些类似的问题,在这里Invoking C compiler using Python subprocess command和subprocess, invoke C-program from within Python,但我相信我的问题在某种意义上是不同的。
我需要编译一个使用一些ROOT库的c ++程序,所以我需要添加一些标志并链接一些库进行编译。因此我在普通shell上的编译行是:
> $($ROOTSYS/bin/root-config --cxx) $($ROOTSYS/bin/root-config --cflags --glibs) Analysis.cxx -o analysis.exe
这很好用。我想从我的python脚本编译。我已经阅读了subprocess模块的文档,但是在subprocess.Popen的调用中没有使用shell=True
我无法得到解决方案,我并没有真正解决这个问题。如果我使用:
process = Popen(["$($ROOTSYS/bin/root-config --cxx) $($ROOTSYS/bin/root-config --cflags --glibs) Analysis.cxx -o analysis.exe"], shell=True)
做的工作。但是,这个:
process = Popen(["$($ROOTSYS/bin/root-config --cxx)", "$($ROOTSYS/bin/root-config --cflags --glibs)", "Analysis.cxx", "-o", "analysis.exe"])
我得到以下内容:
Traceback (most recent call last):
File "make_posanalysis.py", line 45, in <module>
"Analysis.cxx", "-o", "analysis.exe"])
File "Python/2.7.15/x86_64-slc6-gcc62-opt/lib/python2.7/subprocess.py", line 394, in __init__
errread, errwrite)
File "Python/2.7.15/x86_64-slc6-gcc62-opt/lib/python2.7/subprocess.py", line 1047, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
我想了解使用/不使用shell=True
之间的区别,因为它似乎是使脚本工作的原因。或者,还有其他我想念的东西?
如果args是一个序列,则第一个项指定命令字符串,并且任何其他项将被视为shell本身的附加参数。也就是说,Popen相当于:
Popen(['/bin/sh', '-c', args[0], args[1], ...])
所以它执行的东西相当于:
/bin/sh -c '$($ROOTSYS/bin/root-config --cxx)' '$($ROOTSYS/bin/root-config --cflags --glibs)' "Analysis.cxx", "-o", "analysis.exe"
这不是你想要的,因为它只在第一个参数中执行$(...)
扩展;如果第一个参数中的命令引用$1
,$2
等,则其他所有内容都按字面意思取得,并成为位置参数。
如果你想要shell解析的所有东西,只需给出一个字符串。