我有这样的命令。
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/