【问题标题】:Reading from linux command line with Python使用 Python 从 linux 命令行 读取
【发布时间】:2015-09-03 04:29:57
【问题描述】:

有没有办法读取进入命令行的数据,直接进入另一个 Python 脚本执行?

【问题讨论】:

标签: python linux shell command-line


【解决方案1】:

您需要从 python 脚本中读取stdin。

import sys

data = sys.stdin.read()
print 'Data from stdin -', data

示例运行 -

$ date | python test.py
Data from stdin - Wed Jun 17 11:59:43 PDT 2015

【讨论】:

    【解决方案2】:

    使用管道

    x = input()
    

    会变魔术

    【讨论】:

      【解决方案3】:

      这是一个示例,供将来参考,也可以帮助其他人。
      使用 Python 2.6、2.7、3.6 测试

      # coding=utf-8
      """
      Read output from command line passed through a linux pipe
      $ vmstat 1 | python read_cmd_output.py 10 3 10
      This will warn when the column value breached the threshold for N time consecutively
      """
      
      import sys
      import re
      
      def main():
          """ Main """
          values = []
          try:
              column, occurrence, threshold = sys.argv[1:]
              column = int(column)
              occurrence = int(occurrence)
              threshold = int(threshold)
          except ValueError:
              print('Usage: {0} <column> <occurrence> <threshold>'.format(sys.argv[0]))
              sys.exit(1)
      
          with sys.stdin:
              for line in iter(sys.stdin.readline, b''):
                  line = line.strip()
                  if re.match(r'\d', line):
                      elems = re.split(r'\s+', line)
                      values.append(elems[column-1])
                      len(values) > occurrence and values.pop(0)
                      nb_greater = len([x for x in values if int(x) > threshold])
                      print(values, nb_greater, 'Warn' if nb_greater >= len(values) else '')
      
      if __name__ == '__main__':
          try:
              main()
          except KeyboardInterrupt:
              print("\nUser interrupted the script")
              sys.exit(1)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-01-30
        • 2016-01-03
        • 2017-07-30
        • 1970-01-01
        • 2018-04-26
        相关资源
        最近更新 更多