简体   繁体   English

如何在 c++ 中使用 system() 来运行包含空格的 python 脚本

[英]How to use system() in c++ to run python script containing space

I wish to run a python script in c++ code but the address path contains spaces.我希望在 c++ 代码中运行 python 脚本,但地址路径包含空格。
Here is what I'm trying to do:这是我正在尝试做的事情:

string python = "\"D:\\my folder\\python.exe\"";
string script = "\"D:\\my scripts\\hello.py\"";
string arg = "\"argument 1\"";
string cmd= python + " " + script + " " + arg;
system(cmd.c_str());

Here cmd "\"D:\\my folder\\python.exe\" \"D:\\my scripts\\hello.py\"" "\"argument 1\""这里 cmd "\"D:\\my folder\\python.exe\" \"D:\\my scripts\\hello.py\"" "\"argument 1\""
which is in text form, expected to be executed as这是文本形式,预计将被执行为
"D:\my folder\python.exe" "D:\my scripts\hello.py" "argument 1" as command line, but this fails to execute with an error ->'D:\my' is not recognized as an internal or external command. "D:\my folder\python.exe" "D:\my scripts\hello.py" "argument 1" 作为命令行,但这无法执行并出现错误 ->'D:\my' 未被识别为内部或外部命令。

But the same command "D:\my folder\python.exe" "D:\my scripts\hello.py" works fine in command prompt?但是相同的命令 "D:\my folder\python.exe" "D:\my scripts\hello.py" 在命令提示符下工作正常吗?
Please suggest in c++ how to execute python script having space in the path and pass an argument to the script.请在 c++ 中建议如何执行在路径中有空格的 python 脚本并将参数传递给脚本。

Alright, I found a way to get it to work with a system() I tried with exec but still had some issues there.好吧,我找到了一种方法让它与我尝试使用 exec 的 system() 一起工作,但那里仍然存在一些问题。 one needs to cover the entire command in double-quotes.需要用双引号覆盖整个命令。

In my case it should be "\"\"D:\\my folder\\python.exe\" \"D:\\my scripts\\hello.py\"" "\"argument 1\"\""在我的情况下,它应该是"\"\"D:\\my folder\\python.exe\" \"D:\\my scripts\\hello.py\"" "\"argument 1\"\""

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM