【问题标题】:Parameters are ignored in subprocess.Popen [duplicate]subprocess.Popen中忽略参数
【发布时间】:2016-02-20 00:11:27
【问题描述】:

我正在尝试从 python 脚本中运行 shell 命令。这是在 CentOS linux 发行版中运行的。 Python 版本为 2.6.6。

文件系统如下:

bash-4.1$ ls
example.py  file1  file2  file3

脚本example.py如下:

#!/usr/bin/python
import os
import logging
import subprocess
import shlex

if __name__ == "__main__":
    path = os.getcwd()
    command = "touch file1 file2 file3"
    print("Running \"{0}\" at {1}".format(command, path))
    command_as_list = shlex.split(command)
    print("command_as_list = {0}".format(command_as_list))
    process = subprocess.Popen(command_as_list,
                          shell=True,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE,
                          cwd=path)
    if process.wait() == -1:
        raise Exception("Error in command {0}".format(command))

    if process.stderr is not None:
        print("Error ouput: {0}".format(process.stderr.read()))

运行脚本会产生以下输出:

bash-4.1$ ./example.py
Running "touch file1 file2 file3" at /home/example
command_as_list = ['touch', 'file1', 'file2', 'file3']
Error ouput: touch: missing file operand
Try `touch --help' for more information

直接在命令行上运行命令按预期工作:

bash-4.1$ touch file1 file2 file3

看起来file1 file2 file3 部分被忽略了。知道为什么吗?我是否遗漏了与使用 subprocess.Open() 相关的内容?

【问题讨论】:

    标签: python linux subprocess popen


    【解决方案1】:

    如果您将 shell 设置为 True,则不必使用 shlex - 只需将命令作为字符串传递。

    另一种方法是删除shell=True。

    我希望它会有所帮助:)

    UPD:刚刚尝试过 - 它应该可以解决问题。

    【讨论】:

    • 谢谢。事实证明,我可以将它作为 list + shell=False 或 string + shell=True 运行。我从 subprocess 模块的文档中错过了这一点:“如果 shell 为 True,建议将 args 作为字符串而不是序列传递。”但是,由于 shell=True 存在安全隐患,那么我可能最好使用选项 list+shell=False。
    猜你喜欢
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 2011-12-01
    • 2016-04-21
    • 2013-06-14
    相关资源
    最近更新 更多