发布于2020-02-10 15:28 阅读(652) 评论(0) 点赞(29) 收藏(1)
这个方法是直接调用标准C的system() 函数,仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息。
os.system(cmd)的返回值。如果执行成功,那么会返回0,表示命令执行成功。否则,则是执行错误。
使用os.system返回值是脚本的退出状态码,该方法在调用完shell脚本后,返回一个16位的二进制数,低位为杀死所调用脚本的信号号码,高位为脚本的退出状态码。
os.system()返回值为0 linux命令返回值也为0。
os.system()返回值为256,十六位二进制数示为:00000001,00000000,高八位转成十进制为 1 对应 linux命令返回值 1。
os.system()返回值为512,十六位二进制数示为:00000010,00000000,高八位转成十进制为 2 对应 linux命令返回值 2。
1 2 3 | import os result = os.system( 'cat /etc/passwd' ) print (result) # 0 |
os.popen()方法不仅执行命令而且返回执行后的信息对象(常用于需要获取执行命令后的返回信息),是通过一个管道文件将结果返回。通过 os.popen() 返回的是 file read 的对象,对其进行读取 read() 的操作可以看到执行的输出。
1 2 3 | import os result = os.popen( 'cat /etc/passwd' ) print (result.read()) |
1 2 3 4 5 6 7 8 | import commands status = commands.getstatus( 'cat /etc/passwd' ) print (status) output = commands.getoutput( 'cat /etc/passwd' ) print (output) (status, output) = commands.getstatusoutput( 'cat /etc/passwd' ) print (status, output) |
Subprocess是一个功能强大的子进程管理模块,是替换os.system ,os.spawn* 等方法的一个模块。
当执行命令的参数或者返回中包含了中文文字,那么建议使用subprocess。
1 2 3 4 5 6 | import subprocess res = subprocess.Popen( 'cat /etc/passwd' , shell = True , stdout = subprocess.PIPE, stderr = subprocess.STDOUT) # 使用管道 # print res.stdout.read() # 标准输出 for line in res.stdout.readlines(): print line res.stdout.close() # 关闭 |
os.system:获取程序执行命令的返回值。
os.popen: 获取程序执行命令的输出结果。
commands:获取返回值和命令的输出结果。
https://www.jb51.net/article/142787.htm
作者:小兔子乖乖
链接:https://www.pythonheidong.com/blog/article/230686/a2afcce0ba9dce2c4dec/
来源:python黑洞网
任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任
昵称:
评论内容:(最多支持255个字符)
---无人问津也好,技不如人也罢,你都要试着安静下来,去做自己该做的事,而不是让内心的烦躁、焦虑,坏掉你本来就不多的热情和定力
Copyright © 2018-2021 python黑洞网 All Rights Reserved 版权所有,并保留所有权利。 京ICP备18063182号-1
投诉与举报,广告合作请联系vgs_info@163.com或QQ3083709327
免责声明:网站文章均由用户上传,仅供读者学习交流使用,禁止用做商业用途。若文章涉及色情,反动,侵权等违法信息,请向我们举报,一经核实我们会立即删除!