【问题标题】:Execution error when Passing arguments to a python script using os.system. The script takes sys.argv arguments使用 os.system 将参数传递给 python 脚本时执行错误。该脚本采用 sys.argv 参数
【发布时间】:2019-08-17 02:41:43
【问题描述】:

我尝试从 cmd 执行一个简单的 python 命令,例如C:\Users> stat.py < swagger.yaml > output.html,它通过将 swagger.yaml 作为输入参数执行 stat.py 并生成 output.html 文件,它在 cmd 中运行良好。但现在我想通过另一个 python 文件 demo.py 执行我的 stat.py 文件,方法是将值 swagger.yaml 和 output.html 作为 sys.argv[0] 和 sys.argv[1] 在 demo.py 中传递。

我来自 cmd C:\Users> demo.py swagger.yaml output.html 的命令和我的 demo.py 文件如下..

 # my demo.py file ....

import os
import sys

os.system('stat.py < sys.argv[1] > sys.argv[2]')

错误 - 系统找不到指定的文件。
为什么我收到此错误,请帮助解决它..

【问题讨论】:

    标签: python python-2.7 subprocess


    【解决方案1】:

    在普通字符串中,不应用变量解释。因此,您确实要求从名为 sys.argv[1] 的文件中读取(如果文件存在,则可能是 sys.argv1,这要归功于 shell globbing),然后写入名为 sys.argv[2] 的文件。

    如果您想在脚本中使用值sys.argv,您需要将它们格式化为字符串,例如使用 f 字符串(仅限现代 Python 3.6 左右):

    os.system(f'stat.py < {sys.argv[1]} > {sys.argv[2]}')  # Note f at beginning of literal
    

    或在较旧的 Python 2.7 上,使用 str.format:

    os.system('stat.py < {} > {}'.format(sys.argv[1], sys.argv[2]))
    

    请注意,无论您如何切片,这都是危险的; os.system 在 shell 中启动它,包含 shell 元字符的参数将被解释为这样。它不能做任何用户没有权限做的事情,但是用户的小错误可能会极大地改变程序的行为。如果您想正确/安全地执行此操作,请使用subprocess,自己打开文件,并将它们显式传递为stdin/stdout

    with open(sys.argv[1], 'rb') as infile, open(sys.argv[2], 'wb') as outfile:
        subprocess.run(['stat.py'], stdin=infile, stdout=outfile)
    

    这确保了在启动进程之前可以首先打开文件,不允许 shell 解释任何内容,并且完全避免了启动 shell 的(小)费用。如果打开文件失败,它还会为您提供更多有用的错误。

    【讨论】:

      猜你喜欢
      • 2015-05-13
      • 1970-01-01
      • 2017-12-13
      • 2016-09-02
      • 2012-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多