我想在python脚本中获得一些外壳命令的输出,比如ls
或df
。我发现commands.getoutput('ls')
被弃用了,但是subprocess.call('ls')
只会给我返回代码。
我希望有一些简单的解决方案。
发布于 2013-06-27 05:09:13
对于Python >= 2.7,请使用subprocess.check_output()
。
http://docs.python.org/2/library/subprocess.html#subprocess.check_output
发布于 2018-07-13 01:44:54
要使用subprocess.check_output()
捕获错误,可以使用CalledProcessError
。如果您想以字符串的形式使用输出,请从字节码中解码它。
# \return String of the output, stripped from whitespace at right side; or None on failure.
def runls():
import subprocess
try:
byteOutput = subprocess.check_output(['ls', '-a'], timeout=2)
return byteOutput.decode('UTF-8').rstrip()
except subprocess.CalledProcessError as e:
print("Error in ls -a:\n", e.output)
return None
https://stackoverflow.com/questions/6657690
复制相似问题