发布时间:2019-07-25 09:19:55编辑:auto阅读(1301)
1、打开外部程序
1.1
os.system —> 发送命令,让系统执行,没有返回值
os.popen —> 可执行系统命令,可以获取标准输出
lll = os.popen(‘ls’)
lll.read()
os.popen2 —> 元组方式返回标准输入和标准输出
stdin,stdou = os.popen2(‘sort’)
s = ‘’’ e c d b e’’
stdin.write(s)
stdin.close() —> 写入之后必须关闭或flush 才可以读取到数据
stdou.read()
os.popen3 —> 返回标准输入,标准输出,标准错误
pipe_in,pipe_out,pipe_err = os.popen3(‘sort’)
os.popen4 —> 返回标准输入和标准错误
pipe_in,pipe_out_err = os.popen4(‘sort’)
1.2
subprocess
import subprocess
In [14]: subprocess.
subprocess.call subprocess.os
subprocess.CalledProcessError subprocess.pickle
subprocess.check_call subprocess.PIPE
subprocess.check_output subprocess.Popen
subprocess.errno subprocess.select
subprocess.fcntl subprocess.signal
subprocess.gc subprocess.STDOUT
subprocess.list2cmdline subprocess.sys
subprocess.MAXFD subprocess.traceback
subprocess.mswindows subprocess.types
主要方法:call 和check_call
subprocess.call([‘ls’,’-l’],shell = False) —》默认由python执行命令
subprocess.call(‘ls -l’,shell = True) —>利用shell的方式执行命令
subprocess.check_all —》 返回python错误而不是shell错误
可用try捕获异常
try:
subprocess.check_all(‘mkdir aaa’,shell=True)
except Exception;err:
print “error”
subf =subprocess.Popen([‘sort’,’-n’],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stdout=subprocess.PIPE,shell=False) —>从管道中导入标准输入和标准输出
s = ‘’’ s d f g w’’
subf.stdin.write(s)
subf.stdin.close()
print subf.stdou.read()
1.3
import glob
glob.glob(‘a*’) —> 返回以a开头的文件名
1.4 shlex —> 切割模块
import shlex
mysql_conn = ‘mysql -u root -p 123456 -m “hello world”’
args = shlex.split(mysql_conn)
args
subf =subprocess.Popen(shlex.split(mysql_conn),stdout=subprocess.PIPE,stdout=subprocess.PIPE,shell=False)
1.5 PIPE管道
from subprocess import Popen,PIPE
p1 = Popen([‘ls’],stdout = PIPE)
P2 = Popen([‘grep’,’py’],stdin=p1.stdou,stdou=PIPE)
print p2.stdou.read()
p3 = Popen([‘ls’],stdout = open(‘text.txt’,’wb’)) —>结果写入文件里
上一篇: Python 定义函数
下一篇: Python 常用模块
47486
45791
36786
34320
28957
25591
24438
19608
19105
17630
5460°
6043°
5567°
5634°
6569°
5372°
5372°
5880°
5853°
7165°