【问题标题】:How to store the return value of os.system that it has printed to stdout in python? [duplicate]如何在 python 中存储它打印到 stdout 的 os.system 的返回值? [复制]
【发布时间】:2011-10-08 10:27:30
【问题描述】:

我正在编写一个 python 脚本来检查特定 IP / 端口的活动连接数。为此,我使用 os.system('my_command') 来获取输出。 os.system 返回我传递的命令的退出状态(0 表示命令返回没有错误)。 如何将 os.system 抛出给 STDOUT 的值存储在变量中?这样这个变量就可以在后面的函数中用于计数器。 像 subprocess 之类的东西,os.popen 可以提供帮助。有人可以建议吗?

【问题讨论】:

    标签: python


    【解决方案1】:
    import subprocess
    p = subprocess.Popen('my_command', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, error = p.communicate()
    

    【讨论】:

    • 你提到的第三行不是在括号里吗?比如, (out, error) = p.communicate() 然后说 print "结果是:", out
    • 不,在 Python 中,您不需要括号。元组可以隐式创建并自动打包和解包。是的,你可以这样做print 'The output was', out, 'and the error was', error
    • 好的,明白了。这是执行以下 netstat 命令的正确语法吗 -> result = subprocess.Popen(["netstat -plant | awk \'{print $4}\' | grep %s:%s | wc -l' %(ip ,port)"], stdout=subprocess.PIPE, stderr= subprocess.PIPE) ?我收到一个错误:文件“/usr/lib/python2.7/subprocess.py”,第 672 行,在 init errread, errwrite) 文件“/usr/lib/python2.7/subprocess. py",第 1202 行,在 _execute_child raise child_exception OSError: [Errno 2] No such file or directory 为什么我会这样?
    • 请编辑代码并用反引号 ``` 括起来,以便可读。
    • 试试这个result = subprocess.Popen('''sh -c "netstat -plant | awk \'{print $4}\' | grep %s:%s | wc -l' %(ip,port)"''') 编辑:或者用shell=True 试试@Jakob-Bowyer 建议如下。需要,因为您不只是运行一个命令,而是使用 shell 的管道 | 功能。
    【解决方案2】:
    import subprocess
    p = subprocess.Popen('my_command', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    out, error = p.communicate()
    

    【讨论】:

      【解决方案3】:
      netstat -plant | awk '{print $4}' | grep %s:%s | wc -l
      

      您可以使用 Python 进行拆分、grepping 和计数:

      process = subprocess.Popen(['netstat', '-plant'], stdout=subprocess.PIPE)
      
      num_matches = 0
      
      host_and_port = "%s:%s" % (ip, port)
      
      for line in process.stdout:
          parts = line.split()
          if parts[3] == host_and_port: # or host_and_port in parts[3]
              num_matches += 1
      
      
      print num_matches
      

      【讨论】:

      • 这也解决了我的问题;但@agf 的回答是一个班轮
      【解决方案4】:
      a=os.popen("your command").read()
      

      新结果存储在变量a :)

      【讨论】:

      • 正确的对我不起作用,但这个很完美!
      猜你喜欢
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-29
      • 2018-08-28
      • 2014-09-28
      • 1970-01-01
      相关资源
      最近更新 更多