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. 【数组】Find Peak Element

    题目: A peak element is an element that is greater than its neighbors. Given an input array where num[ ...

  2. jetbrains golang IDE

    非常好的IDE,叫goland. 支持最新的golang1.8了 下载地址: https://www.jetbrains.com/go/ 开始使用手册: https://www.jetbrains.c ...

  3. Python&Appium实现安卓手机图形解锁

    首先,在解锁状态下,建立一个Session,打开APP.然后,调用press_keycode()方法传入整型数值"26",锁定屏幕.通过implicitly_wait()方法等待两 ...

  4. Go 协程编程感悟

    0.GPM模型 1.默认地, Go所有的goroutines只能在一个线程里跑 ,除非告诉Go我们允许同时最多使用多个核,或者主动让出CPU时间,使goroutine可以抢占式的执行 2.如果当前go ...

  5. Docker数据管理(数据卷&数据卷容器)

    生产环境中使用Docker的过程中,往往需要对数据进行持久化,或者需要在多个容器之间进行数据共享,这必然涉及容器的数据管理操作. 容器中管理数据主要有两种方式: 数据卷(Data Volumes):容 ...

  6. NoSQL数据库--简介

    一.What's NoSQL? NoSQL,全称是”Not Only Sql”,指的是非关系型的数据库.这类数据库主要有这些特点:非关系型的.分布式的.开源的.水平可扩展的.原始的目的是为了大规模we ...

  7. BG.Hive - part3

    1. Hive数据导入 - Load Load,加载,不会进行任何数据转换和处理的操作,只会进行数据Move操作,将元数据移动到HDFS指定目录 a> hdfs dfs -put 'hdfs的h ...

  8. Angular待办事项应用4——模拟web服务

    内存服务器 angular提供了一个快速建立测试用的web服务方法,内存服务器(in-memory),让我们不用等待后端开发的进度 安装npm包 npm install --save angular- ...

  9. ASP.NET jQuery 事件里调用后台方法

    利用js 调用后台写的方法 <script src="js/jquery-1.7.1.min.js"></script> <script> $( ...

  10. 父页面向iframe子页面传递参数

    父页面: <iframe src="video.html" width="100%" height="400" name=" ...