【问题标题】:How can I run a binary executable with input file (bash command) in Python?如何在 Python 中使用输入文件(bash 命令)运行二进制可执行文件?
【发布时间】:2020-08-01 23:19:48
【问题描述】:

我有一个名为 "abc" 的二进制可执行文件,我有一个名为 "input.txt" 的输入文件。我可以使用以下 bash 命令运行它们:

./abc < input.txt

如何在 Python 中运行此 bash 命令,我尝试了一些方法,但出现错误。

编辑: 我还需要存储命令的输出。

编辑2:

我用这种方法解决了,谢谢你的帮助。

input_path = input.txt 文件的路径。

out = subprocess.Popen(["./abc"],stdin=open(input_path),stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
stdout,stderr = out.communicate()
print(stdout)

【问题讨论】:

  • 你试过用subprocess模块做这个吗?
  • 是的,我尝试了 subprocess 模块,但我不能只运行这个命令。我可以使用子进程轻松运行另一个命令,但它不适用于这个。
  • bash 符号&lt; 表示输入重定向。看看documentation中子进程的标准输入参数

标签: python bash command executable


【解决方案1】:

使用 os.system

import os
os.system("echo test from shell");

【讨论】:

    【解决方案2】:

    使用子进程是调用系统命令和可执行文件的最佳方式。它提供了比 os.system() 更好的控制,并打算取代它。下面的 python 文档链接提供了更多信息。

    https://docs.python.org/3/library/subprocess.html

    这是一段代码,它使用 subprocess 从 head 读取输出以从 txt 文件返回前 100 行并逐行处理。它为您提供输出 (out) 和任何错误 (err)。

    mycmd = 'head -100 myfile.txt'
    (out, err) = subprocess.Popen(mycmd, stdout=subprocess.PIPE, shell=True).communicate()                                  
    myrows = str(out.decode("utf-8")).split("\n")                                                                           
    for myrow in myrows: 
        # do something with myrow
    

    【讨论】:

      【解决方案3】:

      这可以通过os 模块完成。以下代码运行良好。

      import os
      
      path = "path of the executable 'abc' and 'input.txt' file"
      os.chdir(path)
      os.system("./abc < input.txt")
      

      希望这可行:)

      【讨论】:

        猜你喜欢
        • 2020-09-13
        • 2014-01-05
        • 2023-03-30
        • 1970-01-01
        • 2015-07-16
        • 1970-01-01
        相关资源
        最近更新 更多