【问题标题】:Execute shell command and retrieve stdout in Python [duplicate]在Python中执行shell命令并检索标准输出[重复]
【发布时间】:2016-01-29 14:06:09
【问题描述】:

在 Perl 中,如果我想执行 foo 这样的 shell 命令,我会这样做:

#!/usr/bin/perl
$stdout = `foo`

在 Python 中我发现了这个非常复杂的解决方案:

#!/usr/bin/python
import subprocess
p = subprocess.Popen('foo', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout = p.stdout.readlines()
retval = p.wait()

有没有更好的解决方案?

请注意,我不想使用 call 或 os.system。我想将stdout 放在一个变量上

【问题讨论】:

  • 你用的是什么python版本?
  • 为什么不简单:os.system("cd ..")
  • 好吧,在这种情况下你会遇到像stackoverflow.com/q/89228/2088135这样的问题
  • Python 和 Perl 都是高级脚本语言,但具有不同的理念。 Perl 旨在让程序员尽可能少地打字,而 Python 则强制结构整洁以具有易于阅读的代码。出于同样的原因,您也找不到expression unless condition。
  • @TomFenech:我看不出这个问题与您链接的问题有什么关系,即转换路径字符串

标签: python perl shell


【解决方案1】:

一个简单的方法是使用sh 包。 一些例子:

import sh
print(sh.ls("/"))

# same thing as above
from sh import ls
print(ls("/"))

【讨论】:

    【解决方案2】:

    你可以试试这个

    import os
    print os.popen('ipconfig').read()
    #'ipconfig' is an example of command
    

    【讨论】:

      【解决方案3】:

      阅读更多subprocess 文档。它有很多简化的辅助函数:

      output = subprocess.check_output('foo', shell=True, stderr=subprocess.STDOUT)
      

      【讨论】:

      • 另外,在大多数情况下,您可能不需要shell=True,并且出于性能和安全原因一般应避免使用它(类似地,在 Perl 中,出于同样的原因,最好避免使用反引号,在支持 3+ arg open 之类的解决方案并读取生成的文件句柄)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      • 2011-12-28
      • 2020-10-10
      • 2012-10-08
      • 2014-04-18
      • 1970-01-01
      相关资源
      最近更新 更多