【问题标题】:Python subprocess.run shell kwarg behaviorPython subprocess.run shell kwarg 行为
【发布时间】:2019-08-29 07:00:04
【问题描述】:

关于shell 关键字参数有很多问题。但我仍然不明白,尤其是如果我们使用序列参数而不是字符串。

我的理解是,如果shell=Falsesubprocess 模块将在args[0] 中运行可执行文件,并将其余部分作为参数传递给可执行文件。但是如果我们用shell=True 运行它,它就会像"sh -c {}".format(format_escaping(args)) 这样运行。

但是为什么会这样呢?

# Ran in OSX

subprocess.run(["touch", "12; touch 34"]) # successfuly make the file '12; touch 34'

subprocess.run(["touch", "56; touch 78"], shell=True) # does not work:
# usage:
# touch [-A [-][[hh]mm]SS] [-acfhm] [-r file] [-t [[CC]YY]MMDDhhmm[.SS]] file ...
# CompletedProcess(args=['touch', '123; touch 456'], returncode=1)

subprocess.run(["touch", "56; touch 79"], shell=True) 实际发生了什么?

【问题讨论】:

    标签: python shell subprocess


    【解决方案1】:

    我认为使用shell=True 时,supbrocess 只运行第一个parameter,即touch,因此您将成为命令的帮助消息,请改为这样尝试:

    subprocess.run("touch 56; touch 78", shell=True)
    

    【讨论】:

    • 我明白了,那么其余的论点会发生什么?例如当我运行subprocess.run(["touch", "touch"])
    • 你应该把所有的参数放在一个地方
    • 您的第一个示例还将为您提供12; touch 34,以便将其视为第一次触摸的参数,而不是使用 shell=True 时的命令
    • 那么subprocess.run(";".join(commands), shell=True) 是否等同于subprocess.run(commands, shell=True)
    【解决方案2】:

    使用shell=True 传入列表时的行为取决于平台。在类 Unix 平台上,Python 只是传入列表的第一个参数。在 Windows 上,它恰好可以工作,尽管它可能不应该。

    【讨论】:

      猜你喜欢
      • 2016-05-07
      • 1970-01-01
      • 2020-07-20
      • 1970-01-01
      • 2018-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多