网络编程
位置:首页>> 网络编程>> Python编程>> python 执行shell命令并将结果保存的实例

python 执行shell命令并将结果保存的实例

作者:siqi_fighting  发布时间:2023-07-27 20:34:52 

标签:python,shell,命令,结果

方法1: 将shell执行的结果保存到字符串


def run_cmd(cmd):
result_str=''
process = subprocess.Popen(cmd, shell=True,
   stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result_f = process.stdout
error_f = process.stderr
errors = error_f.read()
if errors: pass
result_str = result_f.read().strip()
if result_f:
 result_f.close()
if error_f:
 error_f.close()
return result_str

方法2:将shell执行的结果写入到指定文件


def run_cmd2file(cmd):
fdout = open("file_out.log",'a')
fderr = open("file_err.log",'a')
p = subprocess.Popen(cmd, stdout=fdout, stderr=fderr, shell=True)
if p.poll():
 return
p.wait()
return

来源:https://blog.csdn.net/u010454261/article/details/73379102

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com