python子进程& popen语法无效

时间:2015-07-22 21:00:29

标签: python bash pipe subprocess popen

我是脚本新手。我在bash中有这一行我正在尝试用python编写。

numcpu = ($(cat /proc/cpuinfo | grep 'physical id' | awk '{print $NF}' | sort | uniq | wc -l))

我尝试过使用sub和popen而无法让它工作。这是行:

numcpu = sub.Popen('($(cat /proc/cpuinfo | grep 'physical id' | awk '{print $NF}' | sort | uniq | wc -l))',stdout=sub.PIPE,stderr=sub.PIPE)

它不断抛出错误。关于问题是什么或我能做到的另一种方式的任何想法?我知道可能导入并调用os?

我使用的是Python v2.6,我无法升级。

1 个答案:

答案 0 :(得分:1)

那么,如果你使用字符串中包含的相同引号,Python应该如何知道字符串的开始或结束位置?切换到使用"双引号括起shell命令。

此外,您需要告诉subprocess使用shell来运行命令,否则它只是尝试直接运行命令(因此不支持shell语法):< / p>

numcpu = sub.Popen("($(cat /proc/cpuinfo | grep 'physical id' | awk '{print $NF}' | sort | uniq | wc -l))",
                   shell=True, stdout=sub.PIPE, stderr=sub.PIPE)

您可能只想直接从proc/cpuinfo读取,并在Python中处理:

cpu_ids = set()
with open('/proc/cpuinfo') as cpuinfo:
    for line in cpuinfo:
        if 'physical id' in line:
            cpu_ids.add(line.rsplit(None, 1)[-1])
numcpu = len(cpu_ids)