Search code examples
pythonbashpipesubprocesspopen

python subprocess & popen invalid syntax


I am new to scripting. I have this line in bash I'm trying to write in python.

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

I have tried using sub and popen and couldnt get it to work. Here's the line:

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

It keeps throwing errors. Any ideas on what the problem is or another way I could do it? I know maybe importing and calling os?

I am using Python v2.6 and I can't upgrade.


Solution

  • So how should Python know where the string starts or ends if you use the same quotes as are contained in the string? Switch to using " double quotes to enclose your shell command.

    Also, you'll need to tell subprocess to use a shell to run your command, otherwise it'll just try to run the command directly (and thus not support shell syntax):

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

    You may want to just read from proc/cpuinfo directly, and process that in 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)