【问题标题】:Python subprocess Error 22 - Works while debugging but not when runningPython 子进程错误 22 - 在调试时有效,但在运行时无效
【发布时间】:2021-08-09 01:44:25
【问题描述】:

我正在尝试使用 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()

谁能发现我错过了什么?

【问题讨论】:

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


    【解决方案1】:

    我已经设法解决了这个问题,首先将我的命令和参数创建为字符串,然后使用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

    【讨论】:

      猜你喜欢
      • 2020-11-10
      • 1970-01-01
      • 1970-01-01
      • 2017-08-31
      • 1970-01-01
      • 2015-01-04
      • 2016-11-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多