Abubakar Cool
Abubakar Cool

Reputation: 50

bash command runs through cli fine but not running inside python script

Here is python script it is program which gets current INTERNET speed from cli and saves it in a python variable

from subprocess import PIPE, Popen

def cmdline(command):
    process = Popen(args=command,stdout=PIPE,shell=True)
    return process.communicate()[0]

aa=(cmdline("awk '{if(l1){print ($2-l1)/1024,($10-l2)/1024} else{l1=$2; l2=$10;}}' <(grep eth0 /proc/net/dev) <(sleep 1); <(grep eth0 /proc/net/dev)"))

print(str(aa))

gives error

/bin/sh: 1: Syntax error: "(" unexpected

Upvotes: 0

Views: 69

Answers (1)

chepner
chepner

Reputation: 531055

Popen executes its command by default with /bin/sh, the POSIX shell. It does not recognize the bash extension <(...), which leads to your error. The quickest fix is to specify that you want to use /bin/bash as the shell:

process = Popen(args=command, stdout=PIPE, shell=True, executable="/bin/bash")

A better solution would be to stick with a POSIX-compatible command, so that your Python script doesn't rely on bash being installed in any particular location, or at all. Something like

cmd = '''{
  grep eth0 /proc/net/dev
  sleep 1
  grep eth0 /proc/net/dev
  } | awk '{if(l1){print ($2-l1)/1024,($10-l2)/1024} else{l1=$2; l2=$10;}}'
'''


aa=(cmdline(cmd))

The best solution would be to figure out how to do what you want in Python itself, instead of embedding a shell script.

Upvotes: 2

Related Questions