设为首页 加入收藏

TOP

Python调用外部系统命令(二)
2019-05-23 14:33:14 】 浏览:110
Tags:Python 调用 外部 系统 命令
.1.105 具有 32 字节的数据:
请求超时。
请求超时。


192.168.1.105 的 Ping 统计信息:
    数据包: 已发送 = 2,已接收 = 0,丢失 = 2 (100% 丢失),
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\Python27\lib\subprocess.py", line 186, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'ping -n 2 -w 3 192.168.1.105' returned non-zero exit status 1


(4)subprocess.check_output()


函数原型:check_output(*popenargs, **kwargs)。用法与call()相同。区别是如果执行成功返回的是标准输出内容。如果失败,抛CalledProcessError.异常。


import subprocess


output = subprocess.check_output('ping -n 2 -w 3 192.168.1.104', shell=True)
print output


2、os模块


(1)os.system()


os.system(command) 。调用外部系统命令,返回命令结果码,但是无法获取命令执行输出结果,输出结果直接打印到屏幕终端。


import os


retcode = os.system('ping -n 2 -w 3 192.168.1.104')
if retcode == 0:
    print "%s Success" % (ip,)
else:
    print "%s Fail" % (ip,)


(2)os.popen()


os.popen(command) 。调用外部系统命令,返回命令执行输出结果,但不返回结果吗


import os


output = os.popen('ping -n 2 -w 3 192.168.1.104')
print output


3、commands模块


commands模块用于调用Linux shell命令。测试了下在windows上执行失败。主要有如下3个函数


getoutput(cmd): Return output (stdout or stderr) of executing cmd in a shell.
getstatus(file):Return output of "ls -ld <file>" in a string.
getstatusoutput(cmd):Return (status, output) of executing cmd in a shell.


使用实例如下:


import commands


retcode, output = commands.getstatusoutput('ping -n 2 -w 3 192.168.1.104')
print retcode
print output


总结


在编写程序时可根据使用场景来选择不同的Python调用方法来执行外部系统命令。对于复杂的命令考虑使用subprocess.Popen()完成,如果仅是简单的命令执行,可以使用os.system()完成,如调用windows的暂停程序命令os.system('pause')。


首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Python正则表达式与re模块介绍 下一篇C语言解决百钱买百鸡问题

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目