【问题标题】:Executing linux command with "|" and "'\n'" in Python [duplicate]用“|”执行linux命令和 Python 中的“'\n'” [重复]
【发布时间】:2019-04-13 17:27:59
【问题描述】:

我尝试在 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。

对不起,我阅读了其他问题,但我无法理解。

【问题讨论】:

    标签: python linux


    【解决方案1】:

    | 是一个外壳功能。你需要shell=True。

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

    【讨论】:

    • 这很奇怪,我得到的输出与终端不同。
    • 如果您使用shell=True,您可能希望再次将cmd 的元素合并为一个字符串,而不是让Popen 加入它们。
    • 对不起,我阅读了其他问题,但我无法得到它。
    猜你喜欢
    • 2020-10-10
    • 2014-04-22
    • 2017-07-30
    • 2015-09-05
    • 2021-09-18
    • 1970-01-01
    • 2016-12-03
    • 2012-12-02
    • 1970-01-01
    相关资源
    最近更新 更多