![](/img/trans.png)
[英]Cannot return value from `if __name__ == "__main__"` in a Python script?
[英]Using Main() return value as an argument for a python script
我希望我的 C++ 進程傳遞它們的返回值以打開 python 腳本。
cpp 示例文件
int main()
{
//do something
//process is going to finish and is gonna return, for simplicity, 0
//retval = 0, or whatever the return value is going to be
popen("mypython_script.py retval")
return 0;
}
我的python_script.py
if __name__ == "__main__":
cpp_retval = sys.argv[1]
print(cpp_retval)
我不知道 C++ 文件是否可以按照描述發送它們的返回值,但這只是我想要實現的一般行為。
我還可以控制每個 C++ 進程的父進程:它是另一個 python 腳本,負責打開 C++ 文件並在需要時使用父進程來獲取解決方案,因此如果您有從父進程獲取的解決方案“cpp 示例文件”,非常受歡迎
編輯:我忘了補充一點,我不能要求父 python 進程等待 C++ 程序返回一些東西。 在我的程序中,我絕不可能有任何形式的“等待”。
You can capture the return value of the C++ program from the parent python script, if you run the C++ program using cpp_retval = subprocess.call(...)
, or cpp_retval = subprocesss.run(...).returncode
returncode ( https: //docs.python.org/3/library/subprocess.html )。
然后您可以將其傳遞給其他 python 腳本。 所以,像這樣:
cpp_retval = subprocess.call(["my_cpp_program.exe"])
subprocess.call(["my_python_script.py", str(cpp_retval)])
如果您想直接將 C++ 程序中的值傳遞給 python 腳本,您可以這樣做:
#include <cstdlib> // std::system
#include <string>
int main()
{
const int retval = do_stuff();
std::system((std::string("my_python_script.py") + ' ' + std::to_string(retval)).c_str());
return retval;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.