Search code examples
pythonprocessgrepoperating-systemsystem

Getting the output of os.system in python and processing it after


I am trying to do something like:

f = subprocess.check_output("./script.sh ls -l test1/test2/test.log", shell=True)

when I print f, I get value 0. I tried using subprocess and then read() and even then i dont get the details of the file. I need to verify the size of the file..

Not sure how it can be done.

Any help?

When I used

f = os.system("./script.sh ls -l test1/test2/test.log"), I get the output but does not get saved in f. Something like stdoutput or something..

UPDATED: I used

f = os.popen("./script.sh ls -l test1/test2/test.log 2>&1")

if I ran the same command in quotes above, directly on CLI myself, it works fine but if I used the above in a script OR used s = f.readline(), the script stops, I need to hit "return" before the script can proceed..

Why is that? I need 's' because I need to process it.


Solution

  • You can use subprocess.check_output:

    f = subprocess.check_output("./script.sh ls -l test1/test2/test.log",shell=True)
    print(f)
    

    You can split into a list of individual args without using shell=True:

    f = subprocess.check_output(['./script.sh', 'ls', '-l', 'test1/test2/test.log']))