用“ |”执行linux命令和Python中的“ \ n”

时间:2019-04-13 17:28:00

标签: python linux

我尝试在Python中执行linux命令,但没有任何输出和任何错误。

import subprocess, os
cmd = ["iwconfig", "wlan0", "|", "grep", "ESSID", "|", "awk", "-F:", "'{print $2}'", "|", "sed", "'s/\"//g'"]
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, error = proc.communicate()
print(output.decode("ascii"))

输出应为已连接Wi-Fi的ESSID。

对不起,我读了其他问题,但听不懂。

1 个答案:

答案 0 :(得分:2)

|是一个shell功能。您需要shell=True

proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)