subprocess执行系统命令

call:执行命令,返回状态码

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__Author__ = 'KongZhaGen'
import subprocess
# call模块默认接受列表形式的命令
ret = subprocess.call(['df','-h'], shell=False)
# 当shell=True时,call也可以接受字符串形式的命令
ret = subprocess.call("df -h", shell=True)
# 返回状态码,0正确,非0错误
print ret

check_call:如果状态码是0,

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__Author__ = 'KongZhaGen'
import subprocess ret = subprocess.check_call("df -h")
print ret

check_out:执行结果为0,返回结果,否则抛出异常

#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__Author__ = 'KongZhaGen'
import subprocess ret = subprocess.check_output("df -h")
print ret

subprocess.Popen(...)

用于执行复杂的系统命令

参数:

    • args:shell命令,可以是字符串或者序列类型(如:list,元组)
    • bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲
    • stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
    • preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
    • close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。
      所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。
    • shell:同上
    • cwd:用于设置子进程的当前目录
    • env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
    • universal_newlines:不同系统的换行符不同,True -> 同意使用 \n
    • startupinfo与createionflags只在windows下有效
      将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等

示例:

communicate:执行输入的命令,结果返回为元组(stdout,stderr)
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__Author__ = 'KongZhaGen'
import subprocess # 作为与进程的交互,stdin将命令发送子进程,stdout,stderr读取执行结果,等待进程结束
obj = subprocess.Popen(["ipconfig","-all"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
(out,err) = obj.communicate()
'''
Interact with process: Send data to stdin. Read data from
stdout and stderr, until end-of-file is reached. Wait for
process to terminate. The optional input argument should be a
string to be sent to the child process, or None, if no data
should be sent to the child. communicate() returns a tuple (stdout, stderr).
'''
print out

如果在交互模式下执行多个命令怎么办?

shutil:高级的 文件、文件夹、压缩包 处理模块

1、将文件内容从一个文件拷贝到另一个文件中去,可以是部分数据

def copyfileobj(fsrc, fdst, length=16*1024):
"""copy data from file-like object fsrc to file-like object fdst"""
while 1:
buf = fsrc.read(length)
if not buf:
break
fdst.write(buf)
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__Author__ = 'KongZhaGen'
import shutil fp_src = open("three-level-menu.py",'r')
fp_dst = open("user_lock.key",'w') shutil.copyfileobj(fp_src,fp_dst) fp_src.close()
fp_dst.close()

2、拷贝文件

def copyfile(src, dst):
"""Copy data from src to dst"""
if _samefile(src, dst):
raise Error("`%s` and `%s` are the same file" % (src, dst)) for fn in [src, dst]:
try:
st = os.stat(fn)
except OSError:
# File most likely does not exist
pass
else:
# XXX What about other special files? (sockets, devices...)
if stat.S_ISFIFO(st.st_mode):
raise SpecialFileError("`%s` is a named pipe" % fn) with open(src, 'rb') as fsrc:
with open(dst, 'wb') as fdst:
copyfileobj(fsrc, fdst)
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
__Author__ = 'KongZhaGen'
import shutil shutil.copyfile("three-level-menu.py","user_auth.py")

3、shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变

4、shutil.copystat(src, dst)
拷贝状态的信息,包括:mode bits, atime, mtime, flags

5、shutil.copy(src, dst)
拷贝文件和权限

6、shutil.copy2(src, dst)
拷贝文件和状态信息

7、

shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件

例如:copytree(source, destination, ignore=ignore_patterns('*.pyc', 'tmp*'))

8、shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件

9、shutil.move(src, dst)
递归的去移动文件

10、shutil.make_archive(base_name, format,...)

创建压缩包并返回文件路径,例如:zip、tar

    • base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
      如:www                        =>保存至当前路径
      如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/
    • format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
    • root_dir: 要压缩的文件夹路径(默认当前目录)
    • owner: 用户,默认当前用户
    • group: 组,默认当前组
    • logger: 用于记录日志,通常是logging.Logger对象
#将 /Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录

import shutil
ret = shutil.make_archive("wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test') #将 /Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
import shutil
ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')

python之系统命令的更多相关文章

  1. Python执行系统命令的方法 os.system(),os.popen(),commands

    os.popen():用python执行shell的命令,并且返回了结果,括号中是写shell命令 Python执行系统命令的方法: https://my.oschina.net/renwofei42 ...

  2. python 调用系统命令

    Python执行系统命令一般的用到了四种方法, 第一种是 os.system(),  这个方法比较常用, 使用也简单, 会自动的生成一个进程,在进程完成后会自动退出, 需要注意的是 os.system ...

  3. python调用系统命令 shell命令

    使用python调用系统命令,基本有3种选择: 1. 使用os模块的system方法 import os os.system('ls') 2. 使用os模块的popen方法 import os os. ...

  4. windows linux 使用python执行系统命令并将结果保存到变量

    最近需要用到os.system 发现不能赋值到变量 后查有更新的模块,如下: os.system os.spawn* os.popen* popen2.* commands.* 重新使用content ...

  5. 转 Python执行系统命令的方法

    传送门 Python执行系统命令的方法 http://www.linux-field.com/?p=15 Python中执行系统命令常见方法有两种: 两者均需 import os (1) os.sys ...

  6. Python执行系统命令并获得输出的几种方法

    [root@a upfc]# ./ffmpeg-linux64-v3.3.1 -i a.mp3 ffmpeg version N-86111-ga441aa90e8-static http://joh ...

  7. python 执行系统命令模块比较

    python 执行系统命令模块比较 1.os.system模块 仅仅在子终端运行命令,返回状态码,0为成功,其他为失败,但是不返回执行结果 如果再命令行下执行,结果直接打印出来 >>> ...

  8. Python 调用系统命令的模块 Subprocess

    Python 调用系统命令的模块 Subprocess 有些时候需要调用系统内部的一些命令,或者给某个应用命令传不定参数时可以使用该模块. 初识 Subprocess 模块 Subprocess 模块 ...

  9. python执行系统命令后获取返回值的几种方式集合

    python执行系统命令后获取返回值的几种方式集合 今天小编就为大家分享一篇python执行系统命令后获取返回值的几种方式集合,具有很好的参考价值,希望对大家有所帮助.一起跟随小编过来看看吧 第一种情 ...

  10. Python执行系统命令的方法

    Python中执行系统命令常见方法有两种: 两者均需 import os (1) os.system # 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息 system(command) ...

随机推荐

  1. Oracle11g常用数据字典

    转:https://blog.csdn.net/fulq1234/article/details/79760698 Oracle数据字典的名称由前缀和后缀组成,使用_连接,含义说明如下: dba_:包 ...

  2. 数据库 -- Oracle常用命令

    1.查询账号状态 SELECT USERNAME, ACCOUNT_STATUS FROM DBA_USERS; 解锁账号 ALTER USER scott ACCOUNT UNLOCK 2.创建表空 ...

  3. GCC 编译 Windows API 程序

    前言 这学期学可视化程序设计,要使用 Windows API 绘制界面,由于笔者的笔记本硬盘太小,无法装臃肿的 VS(主要是不想装),也不想用 VC++ 6.0,所以就选用 GCC 来编译. 安装 m ...

  4. 使用Apache Bench对网站性能进行测试

    使用Apache Bench对网站性能进行测试

  5. HTTPS 接入优化建议

      随着网络安全的普及成为共识,部署SSL证书完成HTTPS加密的站点 也随之增多.HTTPS加密能够带来的对身份验证及信息加密等诸多好处,不过想要HTTPS协议发挥更加完美的作用也需要开发者在相应环 ...

  6. 软工网络15-Alpha阶段敏捷冲刺

    一.Alpha 阶段全组总任务 二.各个成员在 Alpha 阶段认领的任务 三. 整个项目预期的任务量 四.明日各个成员的任务安排 任务 预计时长 负责人 授权界面 2h 王华俊 难度选择界面 1h ...

  7. Deep Q-Network 学习笔记(六)—— 改进④:dueling dqn

    这篇同样是完全没看懂 Orz,这里只做实现记录.. 要改动的地方只是在神经网络的最后一层做下调整即可. def create(self): neuro_layer_1 = 3 w_init = tf. ...

  8. ClickOnce 发布WinForm应用程序(非签名方式)

    ClickOnce IIS7发布WinForm应用程序,非签名方式(不勾选签名中的"为ClickOnce清单签名") 一.在D盘上建一个文件夹”MyAppPath”.      该 ...

  9. C#基础笔记(第十三天)

    1.复习泛型集合List<T>Dictionary<Tkey,Tvalue>装箱和拆箱装箱:把值类型转换为引用类型拆箱:把引用类型转换为值类型 我们应该尽量避免在代码中发生装箱 ...

  10. java 全自动生成Excel之ExcelUtil篇(上一篇的升级版 [针对实体类对象的遍历赋值])

    看了上一篇随笔之后可以对本篇有更好的了解! 使用的poi的jar包依然是上一篇的poi-3.17.jar.... import pojo.UserPojo(上一篇里有,这里就不粘贴了!) 不废话了,直 ...