标签:sys man std 异常 plugins 字符 设置 not director
可以执行shell命令的相关模块和函数有:
以上执行shell命令的相关的模块和函数的功能均在 subprocess 模块中实现,并提供了更丰富的功能
call
父进程等待子进程完成
返回退出信息(returncode,相当于Linux exit code)
执行命令,返回状态码,shell=True是表示命令可以字符串
>>> import subprocess >>> ret=subprocess.call(["ls","-l"],shell=False) total 4 -rw-r--r--. 1 root root 260 Feb 23 20:44 scrapy.cfg drwxr-xr-x. 4 root root 156 Feb 25 20:05 sokindle >>> ret=subprocess.call("ls -l",shell=True) total 4 -rw-r--r--. 1 root root 260 Feb 23 20:44 scrapy.cfg drwxr-xr-x. 4 root root 156 Feb 25 20:05 sokindle
check_call
父进程等待子进程完成
返回0
检查退出信息,如果returncode不为0,则举出错误subprocess.CalledProcessError,该对象包含有returncode属性,可用try…except…来检查
shell默认为False,在Linux下,shell=False时, Popen调用os.execvp()执行args指定的程序;shell=True时,如果args是字符串,Popen直接调用系统的Shell来执行args指定的程序,如果args是一个序列,则args的第一项是定义程序命令字符串,其它项是调用系统Shell时的附加参数。
>>> ret=subprocess.check_call(["ls","-l"]) total 4 -rw-r--r--. 1 root root 260 Feb 23 20:44 scrapy.cfg drwxr-xr-x. 4 root root 156 Feb 25 20:05 sokindle >>> print(ret) 0 >>> subprocess.check_call("exit 1",shell=True) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/opt/python36/lib/python3.6/subprocess.py", line 291, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command ‘exit 1‘ returned non-zero exit status 1. >>> subprocess.call("exit 1",shell=True) 1 >>>
check_output,类似check_call
执行命令,如果状态码是 0 ,则返回执行结果,否则抛异常
subprocess.Popen(...)
用于执行复杂的系统命令
参数:
>>> import subprocess >>> subprocess.Popen(["mkdir","t1"]) <subprocess.Popen object at 0x7f7419f0fac8> >>> ret1=subprocess.Popen(["mkdir","t1"]) >>> mkdir: cannot create directory ‘t1’: File exists >>> ret2=subprocess.Popen("mkdir t2",shell=True) >>> ret2=subprocess.Popen("ls -l",shell=True) >>> total 4 -rw-r--r--. 1 root root 260 Feb 23 20:44 scrapy.cfg drwxr-xr-x. 4 root root 156 Feb 25 20:05 sokindle drwxr-xr-x. 2 root root 6 May 25 21:29 t1 drwxr-xr-x. 2 root root 6 May 25 21:30 t2
>>> obj = subprocess.Popen("mkdir t3", shell=True, cwd=‘/home/‘,) >>> obj = subprocess.Popen("ls -l",shell=True,cwd=‘/home‘,) >>> total 23464 drwxr-xr-x. 5 root root 59 Mar 5 17:18 crawl drwxr-xr-x. 3 root root 38 Feb 19 11:40 douban drwxr-xr-x. 3 root root 39 Mar 1 20:52 douban2 drwxr-xr-x. 5 root root 159 Aug 17 2016 features drwxr-xr-x. 3 root root 18 Feb 25 19:52 images drwx------. 14 lx lx 4096 Mar 2 20:59 lx drwxr-xr-x. 22 root root 4096 Aug 17 2016 plugins -rw-r--r--. 1 root root 24015561 Mar 7 20:53 PyDev_5.2.0.zip drwxr-xr-x. 4 root root 78 May 13 21:52 python drwxr-xr-x. 2 root root 6 Feb 16 20:22 python36 drwxr-xr-x. 5 root root 60 May 25 21:30 sokindle drwxr-xr-x. 2 root root 6 May 25 21:36 t3 drwxr-xr-x. 3 root root 122 Feb 17 21:13 tutorial
python基础学习日志day5--subprocess模块
标签:sys man std 异常 plugins 字符 设置 not director
原文地址:http://www.cnblogs.com/lixiang1013/p/6906039.html