python - 通过 C++ 调用系统不一致失败

标签 python c++ bash ubuntu system

我正在尝试在 Ubuntu 上通过 C++ 使用系统调用来启动 Python 脚本。问题是这个命令有时可以工作,但通常情况下,它会失败并抛出两个错误之一:

sh: 1: Syntax error: EOF in backquote substitution
sh: 1: xK-��: not found
我正在使用的代码:
std::string pythonPath = "/home/myuser/Programs/miniconda3/envs/Py37/bin/python3.7";    
std::string viewerScript = "/home/myuser/Projects/Pycharm/MyProject/script.py";
std::string command = pythonPath + " " + viewerScript;
std::thread* t = new std::thread(system, command.c_str());
知道这里发生了什么吗?

最佳答案

c_str 返回的数据缓冲区仅保证在您下次以各种方式访问​​字符串(尤其是销毁它)之前有效。所以如果 command即将超出范围,这是销毁缓冲区的线程与使用 system 中缓冲区的新线程之间的竞争.
而不是用 system 做一个线程作为入口点,使用按值获取字符串的 lambda,使其保持事件状态直到 system完成了。

std::thread* t = new std::thread([command]() { system(command.c_str()); });

关于python - 通过 C++ 调用系统不一致失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67619218/

相关文章:

c++ - 我应该怎么做才能获得 'dynamic' 数组的大小?

c++ - 什么时候应用 ADL?

json - 将文件中的json值设置为redis

linux - Bash - 意外 token `fi'

python - 解析 ad-hoc 树

python - 如何使用过去几个月的最后可用数据填充缺失值?

python - 如何在内部存储和映射变量名称?

python - Cython 具体化属性?

c++ - 在 openGL 中绘制平面

bash - 比较两个文件并输出带标记的文件