【问题标题】:Insert (dynamic) command string in ShellExecute function in C++在 C++ 中的 ShellExecute 函数中插入(动态)命令字符串
【发布时间】:2021-09-16 10:59:07
【问题描述】:

使用 C++(在 Windows 10 上),我试图在 cmd.exe 中执行一个命令,该命令执行一个接受另一个文件(csv 格式)的 python 文件。 我想做的就像我在命令行上输入这样的东西一样:

python3 .\plotCSV.py .\filetoplot.csv

或者更好的模式:

python3 C:\...\Documents\plotCSV.py C:\...\Documents\filetoplot.csv

为此,我正在使用ShellExecute,如下所示:

ShellExecute(NULL, "open", "C:\\Windows\\System32\\cmd.exe", "/c \"python3 C:\...\Documents\plotCSV.py C:\...\Documents\filetoplot.csv\"", NULL, SW_SHOWDEFAULT);

对于所选的 csv 文件(例如 filetoplot.csv),此方法有效。除此之外,对于我所需要的,csv 文件的名称是每次在我的 C++ 程序中生成和更改的,并保存在变量file_name.c_str() 中。所以,如果我在 ShellExecute 中使用它,我有:

ShellExecute(NULL, "open", "C:\\Windows\\System32\\cmd.exe", "/c \"python3 C:\...\Documents\plotCSV.py C:\...\Documents\file_name.c_str()\"", NULL, SW_SHOWDEFAULT);

但不幸的是(显然)它不起作用,因为确实没有一个 csv 文件重命名为“file_name.c_str()”。

我还发现了函数ShellExecuteEx 并想重复相同的过程,我认为该函数应该像这样使用:

SHELLEXECUTEINFO info = {0};

        info.cbSize = sizeof(SHELLEXECUTEINFO);
        info.fMask = SEE_MASK_NOCLOSEPROCESS;
        info.hwnd = NULL;
        info.lpVerb = NULL;
        info.lpFile = "cmd.exe"; 
        info.lpParameters = ("python3 C:\...\Documents\plotCSV.py C:\...\Documents\file_name.c_str()");
        info.lpDirectory = NULL;
        info.nShow = SW_SHOW;
        info.hInstApp = NULL;

        ShellExecuteEx(&info);

但即使在这里它也不起作用(我可能误解了函数的工作原理)。

希望我已经很好地解释了自己,我恳请您就如何进行这方面的工作提出建议。

非常感谢

【问题讨论】:

    标签: c++ shellexecute shellexecuteex


    【解决方案1】:

    您正在尝试在字符串文字中编写代码。
    这在 C++ 中是不可能的!

    您需要先创建动态参数字符串,然后将其传递给函数。
    std::string 具有支持字符串文字 (const char *) 的重载 + 运算符。

    std::string param1 = "/c \"python3 C:\\...\\Documents\\plotCSV.py C:\\...\\Documents\\" + file_name + '\"';
    
    ShellExecute(NULL, "open", "C:\\Windows\\System32\\cmd.exe", param1.c_str(), NULL, SW_SHOWDEFAULT);
    

    【讨论】:

    • 亲爱的@Lev M. 非常感谢您的回答,它有效!
    • 还要感谢@marc_s 对我帖子中的错误进行审核和纠正!
    猜你喜欢
    • 2021-03-12
    • 2011-10-19
    • 2017-01-19
    • 1970-01-01
    • 2018-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多