![](/img/trans.png)
[英]Get a return value from C++ program to a Python script using subprocess
[英]Using subprocess for compiling a c++ program from python script
我知道有一些類似的問題,這里使用Python子進程命令和子 進程調用C編譯器 ,從Python中調用C程序,但我相信我的問題在某種意義上是不同的。
我需要編譯一個使用一些ROOT庫的c ++程序,所以我需要添加一些標志並鏈接一些庫以進行編譯。 因此我在普通shell上的編譯行是:
> $($ROOTSYS/bin/root-config --cxx) $($ROOTSYS/bin/root-config --cflags --glibs) Analysis.cxx -o analysis.exe
這很好用。 我想從我的python腳本編譯。 我已經閱讀了子進程模塊的文檔,但是在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解析的所有東西,只需給出一個字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.