获取返回结果
import subprocess
shell_cmd = "ls -l"
return_cmd = subprocess.run(shell_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, encoding='utf-8',shell=True)
if return_cmd.returncode == 0:
print('命令成功执行')
ret_val = return_cmd.stdout
else:
print('命令执行失败')
sys.exit(1)
只是输出的话
from subprocess import Popen, PIPE, STDOUT
move_data = "ls - l"
def exec_command(command):
move_path = Popen(command, stdout=PIPE, stderr=STDOUT, encoding='utf-8', shell=True)
with move_path.stdout:
for line in iter(move_path.stdout.readline, b''):
if len(line) > 3:
print(line.encode().strip())
else:
break
exitcode = move_path.wait()
return exitcode
y = exec_command(move_data)
print('result:')
print(y)