博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python执行系统命令的方法
阅读量:7010 次
发布时间:2019-06-28

本文共 1903 字,大约阅读时间需要 6 分钟。

http://www.cnblogs.com/xuxm2007/archive/2011/01/17/1937220.html

 Python中执行系统命令常见方法有两种:

两者均需 import os

(1) os.system

# 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息

system(command) -> exit_status

Execute the command (a string) in a subshell.

# 如果再命令行下执行,结果直接打印出来

>>> os.system(
'ls'
)
04101419778.CHM    
bash      document    media      py
-
django   video
11.wmv             
books     downloads   Pictures  python
all
-
20061022       
Desktop   Examples    project    tools

(2) os.popen

# 该方法不但执行命令还返回执行后的信息对象

popen(command [, mode='r' [, bufsize]]) -> pipe

Open a pipe to/from a command returning a file object.

例如:

>>>tmp = os.popen('ls *.py').readlines()

>>>tmp
Out[21]:
['dump_db_pickle.py ',
'dump_db_pickle_recs.py ',
'dump_db_shelve.py ',
'initdata.py ',
'__init__.py ',
'make_db_pickle.py ',
'make_db_pickle_recs.py ',
'make_db_shelve.py ',
'peopleinteract_query.py ',
'reader.py ',
'testargv.py ',
'teststreams.py ',
'update_db_pickle.py ',
'writer.py ']

 

 

好处在于:将返回的结果赋于一变量,便于程序的处理。

(3)  使用模块subprocess

import  
subprocess
subprocess.call ([
"cmd"
"arg1"
"arg2"
],shell
=
True
)

获取返回和输出:

import  
subprocess
=  
subprocess.Popen(
'ls'
, shell
=
True
, stdout
=
subprocess.PIPE, stderr
=
subprocess.STDOUT)
for  
line 
in  
p.stdout.readlines():
    
print  
line,
retval 
=  
p.wait()

(4)  使用模块commands模块

>>> import commands

>>> dir(commands)
['__all__', '__builtins__', '__doc__', '__file__', '__name__', 'getoutput', 'getstatus','getstatusoutput', 'mk2arg', 'mkarg']
>>> commands.getoutput("date")
'Wed Jun 10 19:39:57 CST 2009'
>>>
>>> commands.getstatusoutput("date")
(0, 'Wed Jun 10 19:40:41 CST 2009')

 

注意: 当执行命令的参数或者返回中包含了中文文字,那么建议使用subprocess,如果使用os.popen则会出现下面的错误:

Traceback (most recent call last):

File "./test1.py", line 56, in <module>
main()
File "./test1.py", line 45, in main
fax.sendFax()
File "./mailfax/Fax.py", line 13, in sendFax
os.popen(cmd)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 46-52: ordinal not inrange(128)

 

关于本文更多的延伸阅读地址:

你可能感兴趣的文章
MacBook 经常使用快捷键
查看>>
PMP杂谈--PMP中一些easy忽视的地方
查看>>
oracle编码转换:AL32UTF8->ZHS16GBK
查看>>
Unity Update 具体解释
查看>>
T-SQL动态查询(4)——动态SQL
查看>>
Ubuntu 16.04安装uGet替代迅雷,并在Chrome中设置为默认下载器
查看>>
MySQL缓存之Qcache与buffer pool对比
查看>>
springmvc(一) springmvc框架原理分析和简单入门程序
查看>>
别踩白块儿
查看>>
跟面试官讲Binder(零)
查看>>
mahout in Action2.2-聚类介绍-K-means聚类算法
查看>>
bootstrap-treeview 如何实现全选父节点下所有子节点及反选
查看>>
HTML5 CSS3 诱人的实例: 3D立方体旋转动画
查看>>
ElasticSearchserver操作命令
查看>>
ThreadPoolExecutor异常处理
查看>>
LeetCode 第 342 题(Power of Four)
查看>>
用QT搭建简单的播放器外壳
查看>>
索引设计指南
查看>>
Timus Online Judge 1057. Amount of Degrees(数位dp)
查看>>
jquery中关于表格行的增删问题
查看>>