iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python 之调用系统命令
  • 448
分享到

Python 之调用系统命令

命令系统Python 2023-01-31 01:01:29 448人浏览 薄情痞子

Python 官方文档:入门教程 => 点击学习

摘要

在python中执行系统命令的方法有以下几种:1.os.system(command)>>> s = os.system('ls -l') 总用量 56 drwxr-xr-x. 2 root root 4096 4月

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为字符串

















--结束END--

本文标题: Python 之调用系统命令

本文链接: https://www.lsjlt.com/news/183999.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作