python - 如何从外部命令结合管道获取输出

标签 python linux pipe

我有这样的命令。

wmctrl -lp | awk '/gedit/ { print $1 }'

我想在 python 脚本中输出它,我试过这段代码

>>> import subprocess
>>> proc =  subprocess.Popen(["wmctrl -lp", "|","awk '/gedit/ {print $1}"], shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> proc.stdout.readline()
'0x0160001b -1 6504   beer-laptop x-nautilus-desktop\n'
>>> proc.stdout.readline()
'0x0352f117  0 6963   beer-laptop How to get output from external command combine with Pipe - Stack Overflow - Chromium\n'
>>> proc.stdout.readline()
'0x01400003 -1 6503   beer-laptop Bottom Expanded Edge Panel\n'
>>> 

看来我的代码是错误的,只有 wmctrl -lp 被执行了,而 | awk '{print $1}' 被省略 我期望的输出是 0x03800081

$ wmctrl -lp | awk '/gedit/ {print $1}'
0x03800081

有人帮忙吗

最佳答案

使用 shell=True 时,您应该使用单个命令行而不是数组,否则您的附加参数将被解释为 shell 参数。来自subprocess documentation :

On Unix, with shell=True: If args is a string, it specifies the command string to execute through the shell. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional shell arguments.

所以你的电话应该是:

subprocess.Popen("wmctrl -lp | sed /gedit/ '{print $1}'", shell=True, ...

我想你可能还有一个不平衡的单引号。

关于python - 如何从外部命令结合管道获取输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1404693/

相关文章:

python - 将字典打印到表格中

python - 列表Python中的重复元素

c++ - Linux 中的库链接

linux - 当我在脚本运行时编辑它会发生什么?

c - mod_fcgid windows 命名管道 2nd 和后续请求

C 程序拒绝管道?

python - 两个元组作为Python列表中的一个元素

c - C 遍历链表,陷入循环

node.js - NodeJS 中的 `pipe` 方法是什么?

python - 在Python中查找0-100之间的值范围内的索引