【问题标题】:Executing shell command in python with file as stdin在python中执行shell命令,文件为stdin
【发布时间】:2013-05-21 14:07:29
【问题描述】:

在我的 Python 代码中,我有

executable_filepath = '/home/user/executable'
input_filepath = '/home/user/file.in'

我想分析我在 shell 中从命令得到的输出

/home/user/executable </home/user/file.in

我试过了

command = executable_filepath + ' <' + input_filepath
p = subprocess.Popen([command], stdout=subprocess.PIPE)
p.wait()
output = p.stdout.read()

但它不起作用。我现在能想到的唯一解决方案是创建另一个管道,并通过它复制输入文件,但必须有一个简单的方法。

【问题讨论】:

    标签: python shell pipe


    【解决方案1】:
    from subprocess import check_output
    
    with open("/home/user/file.in", "rb") as file:
        output = check_output(["/home/user/executable"], stdin=file)
    

    【讨论】:

      【解决方案2】:

      您需要在对Popen 的调用中指定shell=True。默认情况下,[command] 直接传递给 exec 系列中的系统调用,它不理解 shell 重定向运算符。

      或者,您可以让Popen 将进程连接到文件:

      with open(input_filepath, 'r') as input_fh:
          p = subprocess.Popen( [executable_filepath], stdout=subprocess.PIPE, stdin=input_fh)
          p.wait()
          output=p.stdout.read()
      

      【讨论】:

      • 如果子进程产生足够的输出,在.stdout.read()之前调用.wait()会导致死锁。
      猜你喜欢
      • 2022-08-18
      • 1970-01-01
      • 2013-08-25
      • 2015-03-08
      • 2012-08-28
      • 2020-05-23
      • 1970-01-01
      • 2020-11-06
      • 1970-01-01
      相关资源
      最近更新 更多