Python 子进程错误 22 - 在调试时有效,但在运行时无效

时间:2021-05-19 19:20:25

标签: python-3.x subprocess arguments command-line-arguments

我正在尝试使用 subprocess.Popen() 从另一个调用 python 脚本。当我逐行调试程序时,它运行良好,但是当我正常运行程序时,出现以下错误:

C:\Python38\python.exe: can't open file '"<filepath>\thumbs.py"': [Errno 22] Invalid argument

我对问题是什么感到困惑,因为在逐行调试程序时它可以正常工作,因此不确定程序正常运行时究竟发生了什么变化。

我正在尝试将一组参数传递给子进程,然后在子进程中使用 argparse 解析这些参数。

这就是我调用过程的方式:

cmd = ['python', "\"" + pythonPath + "thumbs.py\"", '-d', "\"" + outputdb + "\"", '-c', "\"" + path + cache + "\""]
subprocess.Popen(cmd).wait()

这是我在子进程中解析参数的方式:

if __name__ == '__main__':
    global session
    args = None
    parser = argparse.ArgumentParser()

    parser.add_argument("-d", "--database", action="store", dest="dbname", help="Database to output results to", required=True)

    parser.add_argument("-c", "--cache", action="store", dest="cachefile", help="Cache file to scrape.", required=True)
    
    while args is None:
        args = parser.parse_args()

谁能发现我遗漏了什么?

1 个答案:

答案 0 :(得分:0)

我已通过首先将命令和参数创建为字符串,然后使用 shlex.Split() 将其拆分为参数列表来解决此问题。

cmdStr = "python \"" + pythonPath + "thumbs.py\" -d \"" + outputdb + "\" -c \"" + path + cache + "\""
cmd = shlex.split(cmdStr)
subprocess.Popen(cmd).wait()

更多信息在这里:https://docs.python.org/3.4/library/subprocess.html#popen-constructor