前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Python 之调用系统命令

Python 之调用系统命令

作者头像
py3study
发布2020-01-14 01:48:43
6160
发布2020-01-14 01:48:43
举报
文章被收录于专栏:python3python3

在python中执行系统命令的方法有以下几种:

1.os.system(command)

代码语言:javascript
复制
>>> 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()

代码语言:javascript
复制
#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()

代码语言:javascript
复制
>>> 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)

代码语言:javascript
复制
>>> 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为字符串

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-07-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档