【问题标题】:Replicate os.system functionality with subprocess in Python? [duplicate]在 Python 中使用子进程复制 os.system 功能? [复制]
【发布时间】:2016-05-23 14:55:25
【问题描述】:

在我的程序中,我想让用户运行 shell 命令或执行二进制文件。不管我读了多少关于subprocess.Popen 的文章,我都无法找到复制os.system() 功能的方法。

我只是想echo $USER,但似乎没有任何效果。

shell=True..

>>> subprocess.Popen(['echo', '$USER'], shell=True,\
                     stdout=subprocess.PIPE,\
                     stderr=subprocess.PIPE).communicate()
>>> ('\n', '')

传递当前环境变量..

>>> subprocess.Popen(['echo', '$USER'], shell=True,\
                     env=os.environ\
                     stdout=subprocess.PIPE,\
                     stderr=subprocess.PIPE).communicate()
>>> ('\n', '')

那么运行 shell 命令的正确方法是什么?

------- 编辑:要求 ---------

有些人发布了答案,但也许我应该更具体。我想同时保留 stdoutstderr 和返回 value stored 某处。所有答案似乎都给出了一个或另一个。

【问题讨论】:

标签: python shell subprocess environment-variables os.system


【解决方案1】:

使用call方法

subprocess.call('echo $USER',shell=True)

Altarnetivly:

var = subprocess.check_output('echo $USER',shell=True) # .rstrip('\n')
print var

还有subprocess.Popen()

process = subprocess.Popen("echo $USER",shell=True,stdout=subprocess.PIPE)
print process.communicate()[0],

【讨论】:

  • 这似乎可行,但我似乎无法将输出保存在变量中..
  • @Pithikos 然后选择check_output
  • 谢谢,这行得通。然后虽然我没有得到返回码。这就是我开始使用 Popen 的原因。我更愿意保留所有标准错误、标准输出、返回代码。
【解决方案2】:

感谢massiou的指导,我找到了答案。罪魁祸首是,当使用shell=True 时,您应该将整个命令作为单个字符串

>>> subprocess.Popen(['echo $USER'], shell=True, \
                     stdout=subprocess.PIPE,\
                     stderr=subprocess.PIPE).communicate()
>>> ('manos\n', '')

原因是列表中的第一个参数将作为 shell 脚本执行。其余参数用于 shell 程序本身。

【讨论】:

    【解决方案3】:

    你可以这样做:

    subprocess.call('echo $USER', shell=True)
    

    另外,看看Replacing Older Functions with the subprocess Module

    【讨论】:

      猜你喜欢
      • 2015-01-23
      • 1970-01-01
      • 2014-04-29
      • 2021-06-06
      • 2012-02-10
      • 1970-01-01
      • 2021-02-13
      • 2011-09-12
      • 2011-03-01
      相关资源
      最近更新 更多