Python 之调用系统命令
2014-04-23 17:41
330 查看
在python中执行系统命令的方法有以下几种:
1.os.system(command)
在python2.7以上的版本,subprocess模块提供了一个可以直接获得输出的函数
check_output(*popenargs, **kwargs)
1.os.system(command)
>>> s = os.system('ls -l') 总用量 56 drwxr-xr-x. 2 root root 4096 4月 16 16:39 down_scripts -rw-r--r--. 1 root root 30 4月 18 11:29 ip.list drwxr-xr-x. 2 root root 4096 4月 23 16:30 mypython drwxr-xr-x. 2 root root 4096 4月 22 09:57 mysource drwxr-xr-x. 3 root root 4096 4月 17 11:51 mywork drwxr-xr-x. 2 root root 36864 3月 19 11:09 pythoncook >>> print s 0 >>> s = os.system('ll -5') sh: ll: command not found >>> print s 32512 #返回值是命令的退出状态。不能扑捉输出的内容2.subprocess.call()
#subprocess.call()执行命令,返回的值是退出信息 >>> s = subprocess.call('ls -l',shell=True) 总用量 56 drwxr-xr-x. 2 root root 4096 4月 16 16:39 down_scripts -rw-r--r--. 1 root root 30 4月 18 11:29 ip.list drwxr-xr-x. 2 root root 4096 4月 24 14:58 mypython drwxr-xr-x. 2 root root 4096 4月 22 09:57 mysource drwxr-xr-x. 3 root root 4096 4月 17 11:51 mywork drwxr-xr-x. 2 root root 36864 3月 19 11:09 pythoncook >>> print s 0 >>> s = subprocess.call(['ls','-l']) 总用量 56 drwxr-xr-x. 2 root root 4096 4月 16 16:39 down_scripts -rw-r--r--. 1 root root 30 4月 18 11:29 ip.list drwxr-xr-x. 2 root root 4096 4月 24 14:58 mypython drwxr-xr-x. 2 root root 4096 4月 22 09:57 mysource drwxr-xr-x. 3 root root 4096 4月 17 11:51 mywork drwxr-xr-x. 2 root root 36864 3月 19 11:09 pythoncook >>> print s 0 #指令可以是字符串,也可以是列表,但是当是字符串时后面跟参数shell=True 该方式相当于创建个新进程执行系统命令,返回值是进程的退出状态。3.subprocess.Popen()
>>> s = subprocess.Popen('ls -l',shell=True,stdout=subprocess.PIPE) >>> print s.stdout.read() 总用量 56 drwxr-xr-x. 2 root root 4096 4月 16 16:39 down_scripts -rw-r--r--. 1 root root 30 4月 18 11:29 ip.list drwxr-xr-x. 2 root root 4096 4月 24 14:58 mypython drwxr-xr-x. 2 root root 4096 4月 22 09:57 mysource drwxr-xr-x. 3 root root 4096 4月 17 11:51 mywork drwxr-xr-x. 2 root root 36864 3月 19 11:09 pythoncook #这方法可获得输出。
在python2.7以上的版本,subprocess模块提供了一个可以直接获得输出的函数
check_output(*popenargs, **kwargs)
>>> s = subprocess.check_output('ls -l',shell=True) >>> print s 总用量 24 -rw-r--r--. 1 root root 150 5月 12 17:30 ip.txt -rwxr-xr-x. 1 root root 235 5月 12 17:57 jiang.py drwxr-xr-x. 2 root root 4096 5月 8 17:18 mypython drwxr-xr-x. 2 root root 4096 5月 12 13:47 mysource drwxr-xr-x. 4 root root 4096 5月 12 16:02 mywork drwxr-xr-x. 3 root root 4096 5月 10 11:37 web此时s为字符串
相关文章推荐
- python模块:调用系统命令模块subprocess等
- Python简明教程中压缩存档例子:正常调用压缩命令(Windows系统下)
- 用python调用系统命令并获得返回
- Python 调用系统命令
- python 调用系统命令 获取返回内容
- python实用程序-HTTP服务调用系统命令(带白名单)
- Python用subprocess的Popen来调用系统命令
- Nodejs中调用系统命令、Shell脚本和Python脚本的方法和实例
- python调用linux系统命令
- Python用subprocess的Popen来调用系统命令
- Python用subprocess的Popen来调用系统命令
- python 如何判断调用系统命令是否执行成功
- python 调用Linux系统命令笔记
- Python用subprocess的Popen来调用系统命令
- python 调用系统命令,并将输出重定向,输出其结果至文件或者字符串变量
- python 调用系统命令,执行命令行
- python 调用系统命令
- Python调用系统命令设置超时时间
- Python用subprocess的Popen来调用系统命令
- python 调用linux系统命令