-1

I have a python script which runs in Linux. I need to capture a command's output and store into variables and then should print the output. Code below -

#!/usr/bin/python
import os, time
systime=os.popen('date +"%m-%d-%y-%T"').read()
os.system("read c1 c2 c3 c4 c5 c6 < <(sar -u 1 1 | awk 'NR==4, NR==4 {print $4, $5, $6, $7, $8, $9}')")
os.system("echo $systime,$c1,$c2,$c3,$c4,$c5,$c6 >> outputfile.txt")

I'm collecting the output given by the command sar -u 1 1 | awk 'NR==4, NR==4 {print $4, $5, $6, $7, $8, $9}') into 6 variables - c1, c2, c3, c4, c5 c6 using the read command. When i try to execute the above code, I get the below error -

sh: -c: line 0: syntax error near unexpected token `<'

I even tried using os.popen instead of os.system but still end up getting the same error. Suggest me on how to store the variables using os.system command how to use them in the later stages. My target here is to print all the variables including the time being captured into a output file outputfile.txt. TIA

  • process substitution is a bash feature, so you'll need to tell python to use bash. – muru Feb 8 '18 at 6:57
2

<(...) is ksh syntax also recognised by zsh and bash, though when used as the target of a redirection, it's only supported by zsh and bash.

In any case, that is not sh syntax. Python's os.system() and os.popen() do run sh to interpret the given command line. And each invocation of those commands runs a new shell, so one variable defined in one will not be available in a the next shell invocation. Also python variables do not automagically become shell variables.

Here, you could do:

os.system("""
  sar -u 1 1 |
    awk -v t="$(date +%m-%d-%y-%T)" -v OFS=, '
      NR==4 {
        print t, $4, $5, $6, $7, $8, $9
      }' > outputfile.txt""")

Though it feels silly to invoke date and awk (or even a shell) from within python while python is very well capable of doing their jobs itsef.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.