mathmaniage
mathmaniage

Reputation: 319

system call that prints output as in the terminal

A terminal command that we type in the terminal might print some output on the terminal. When we use this command in a python script and call a system call say:

os.system('ls')  

we do obtain the output, but somehow it returns an integer to indicate a successful execution of the process:

>>> x = os.system('ls')    #prints some output
>>> x
>>> 0

I need a function that stores the output in x as a string that I need to parse. What is the python function that does this?

Upvotes: 0

Views: 196

Answers (1)

matt
matt

Reputation: 12346

You would use the subprocess module.

from subprocess import PIPE, Popen
proc = Popen(["ls"], stdout=PIPE)
stdout, stderr = proc.communicate()

Or if you're using Python 3.5 or greater, then run is recommended.

import subprocess

completed = subprocess.run(["ls", "-l"], stdout=subprocess.PIPE, encoding="utf-8")

#output is stored in completed.stdout

Upvotes: 1

Related Questions