【问题标题】:Executing linux command using python subprocess使用python子进程执行linux命令
【发布时间】:2022-10-19 00:44:09
【问题描述】:

我有一个要求,我需要从文件example.ini 中提取端口号,该文件位于 linux 目录中。

现在,当我从 CLI 执行以下命令时,它会给出我想要的确切结果

$ cat path/example.ini | grep -i variable | cut -d '=' -f 2

但是我想使用 subprocess.run 使用 python 脚本运行这个命令

我正在脚本中执行

subprocess.run(['cat', 'path', '|', 'grep -i variable', '|', 'cut -d "=" -f2'])

我收到错误:No such file or directory

【问题讨论】:

  • 好像你写的是path 而不是path/example.ini
  • 例如,我在这里写的实际命令是 cat /var/tmp/backup/agent.ini

标签: python linux grep subprocess


【解决方案1】:

为什么将 cat 与 grep 一起使用? grep -i 变量路径/example.ini |剪切 -d '=' -f 2

import subprocess

ps = subprocess.Popen(('grep', '-i', 'variable', 'path/example.ini'), stdout=subprocess.PIPE)
output = subprocess.check_output(('cut', '-d', '=', '-f', '2'), stdin=ps.stdout)
ps.wait()
print(output.decode("utf-8")) # bytes object to UTF8

我简化了我的解决方案

import subprocess

ps = subprocess.Popen(('grep', '-i', 'variable', 'path/example.ini'), stdout=subprocess.PIPE)
output = subprocess.run(('cut', '-d', '=', '-f', '2'), stdin=ps.stdout).stdout

【讨论】:

  • 谢谢你。我现在可以运行,我们也可以使用 res = os.popen('linux command').read() 运行此命令
最近更新 更多