0

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
8
  • missing the python shebang? Commented Apr 7, 2018 at 12:53
  • why are you calling awk from python when python can do the same thing. Commented Apr 7, 2018 at 12:54
  • how can this be done without awk Commented Apr 7, 2018 at 12:57
  • 1
    I don't know much Python, hence just a comment not an answer, but I think that Python uses /bin/sh rather than bash as the shell and I think <(...) is a bash-ism. Commented Apr 7, 2018 at 13:56
  • 1
    @MarkSetchell That is exactly right on both points. Commented Apr 7, 2018 at 14:00

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Its still not working man, thanks for you help but now its giving me this error. /bin/sh: 5: Syntax error: Unterminated quoted string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.