您的位置:首页 > 编程语言 > Python开发

Python 之调用系统命令

2014-04-23 17:41 330 查看
在python中执行系统命令的方法有以下几种:
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 command