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. 【Express系列】第3篇——接入mysql

    通常来说,前后端分离的项目,前端负责界面渲染和操作型的业务逻辑,后端则负责数据存取和数据处理相关的业务逻辑. 既然设计数据,那就少不了数据库的使用.目前市面上流行着各种各样的数据库,这里不打算一一列举 ...

  2. LR问题集合

    LR如何解决低维不可分 特征映射:通过特征变换的方式把低维空间转换到高维空间,而在低维空间不可分的数据,到高维空间中线性可分的几率会高一些.具体方法:核函数,如:高斯核,多项式核等等. 从图模型角度看 ...

  3. 在 mac 上利用 homebrew 安装软件

    在mac经常需要安装一些软件,你可以通过app store下载,或者可以通过浏览袭搜索下载.这里介绍通过homebrew安装一些软件,它会自动为你下载一些软件的相关依赖,免去安装的烦恼. 首先我们需要 ...

  4. SpringMvc注解开发

    1.四大注解的定义 (1)Controller注解:该注解使用在一个类上面,参数为value,值为访问该controller的名称,默认为空,如果为空 则值为该controller类名的首字母小写的值 ...

  5. Angular的第一个helloworld

    在安装了node,npm,angular-cli,vscode之后,我们来创建一个angular的应用 创建第一个hello world 使用的IDE工具为vscode 打开vscode,打开一个命令 ...

  6. Head First Python学习笔记3——持久存储

    经过上几章的学习,完成如下任务:读取一个文本文件里的内容,将每一行的内容按“:”分割成两部分,根据分割出第一项判断并分别放入两个列表里,去除首尾空白,在屏幕上打印. # 两个列表用于存储数据man=[ ...

  7. oracle一个listener侦听多个实例的配置

    https://blog.csdn.net/silesilesile/article/details/79725337

  8. JAVA编写简单的日历,输入日期即可查看日历

    利用LocalDate输入年月日找出当月日历 直接上代码 import java.time.LocalDate; import java.util.Scanner; public class Cale ...

  9. python 历险记(五)— python 中的模块

    目录 前言 基础 模块化程序设计 模块化有哪些好处? 什么是 python 中的模块? 引入模块有几种方式? 模块的查找顺序 模块中包含执行语句的情况 用 dir() 函数来窥探模块 python 的 ...

  10. Spark of work

    Today I attended a meeting of reviewing code,  and I learned a lot from it. In the discuss, we found ...