in python, get the output of system command as a s

2019-01-17 06:31发布

This question already has an answer here:

In python I can run some system command using os or subprocess. The problem is that I can't get the output as a string. For example:

>>> tmp = os.system("ls")
file1 file2
>>> tmp
0

I have an older version of subprocess that doesn't have the function check_out, and I would prefer a solution that doesn't require to update that module since my code will run on a server I don't have full admin rights.

This problem seems trivial, yet I couldn't find a trivial solution

1条回答
混吃等死
2楼-- · 2019-01-17 07:26

Use os.popen():

tmp = os.popen("ls").read()

The newer way (> python 2.6) to do this is to use subprocess:

proc = subprocess.Popen('ls', stdout=subprocess.PIPE)
tmp = proc.stdout.read()
查看更多
登录 后发表回答