我有这样的代码os.system(mycommand)
。我想把批处理命令的结果作为字符串。我怎么能这样做?
答案 0 :(得分:4)
Python的subprocess
模块在Python 2.7中有built-in function这样做。
import subprocess
try:
mycommand = "ls"
result = subprocess.check_output(mycommand, shell=True)
print(result)
except subprocess.CalledProcessError as error:
# Handle the error
print("Error: Command exited with code {0}".format(error.returncode))