Raf*_*l T 60 python shell command subprocess
我想从像一些shell命令得到的输出ls
或者df
在Python脚本.我看到它commands.getoutput('ls')
已被弃用,但subprocess.call('ls')
只会给我返回代码.
我希望有一些简单的解决方案.
Mic*_*ith 86
使用subprocess.Popen:
import subprocess
process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE)
out, err = process.communicate()
print(out)
Run Code Online (Sandbox Code Playgroud)
请注意,通信阻塞直到进程终止.如果在终止之前需要输出,则可以使用process.stdout.readline().有关更多信息,请参阅文档.
kni*_*ite 47
对于Python> = 2.7,请使用subprocess.check_output()
.
http://docs.python.org/2/library/subprocess.html#subprocess.check_output
要捕获错误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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
81644 次 |
最近记录: |