在python中,获取系统命令的输出作为字符串 [英] in python, get the output of system command as a string
问题描述
在python我可以运行一些系统命令使用os或子进程。问题是,我不能得到一个字符串的输出。例如:
>>> tmp = os.system(ls)
file1 file2
>>> tmp
0
我有一个旧版本的子进程没有check_out ,我更喜欢一个解决方案,不需要更新该模块,因为我的代码将运行在服务器上,我没有完全的管理权限。
这个问题似乎微不足道,但我找不到一个简单的解决方案。
使用 os.popen()
:
tmp = os.popen(ls)。read()
更新的方法(> python 2.6)要使用 subprocess
:
proc = subprocess.Popen('ls',stdout = subprocess.PIPE)
pre>
tmp = proc.stdout.read()
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
解决方案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()
这篇关于在python中,获取系统命令的输出作为字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!