python之系统命令
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之系统命令的更多相关文章
- Python执行系统命令的方法 os.system(),os.popen(),commands
os.popen():用python执行shell的命令,并且返回了结果,括号中是写shell命令 Python执行系统命令的方法: https://my.oschina.net/renwofei42 ...
- python 调用系统命令
Python执行系统命令一般的用到了四种方法, 第一种是 os.system(), 这个方法比较常用, 使用也简单, 会自动的生成一个进程,在进程完成后会自动退出, 需要注意的是 os.system ...
- python调用系统命令 shell命令
使用python调用系统命令,基本有3种选择: 1. 使用os模块的system方法 import os os.system('ls') 2. 使用os模块的popen方法 import os os. ...
- windows linux 使用python执行系统命令并将结果保存到变量
最近需要用到os.system 发现不能赋值到变量 后查有更新的模块,如下: os.system os.spawn* os.popen* popen2.* commands.* 重新使用content ...
- 转 Python执行系统命令的方法
传送门 Python执行系统命令的方法 http://www.linux-field.com/?p=15 Python中执行系统命令常见方法有两种: 两者均需 import os (1) os.sys ...
- Python执行系统命令并获得输出的几种方法
[root@a upfc]# ./ffmpeg-linux64-v3.3.1 -i a.mp3 ffmpeg version N-86111-ga441aa90e8-static http://joh ...
- python 执行系统命令模块比较
python 执行系统命令模块比较 1.os.system模块 仅仅在子终端运行命令,返回状态码,0为成功,其他为失败,但是不返回执行结果 如果再命令行下执行,结果直接打印出来 >>> ...
- Python 调用系统命令的模块 Subprocess
Python 调用系统命令的模块 Subprocess 有些时候需要调用系统内部的一些命令,或者给某个应用命令传不定参数时可以使用该模块. 初识 Subprocess 模块 Subprocess 模块 ...
- python执行系统命令后获取返回值的几种方式集合
python执行系统命令后获取返回值的几种方式集合 今天小编就为大家分享一篇python执行系统命令后获取返回值的几种方式集合,具有很好的参考价值,希望对大家有所帮助.一起跟随小编过来看看吧 第一种情 ...
- Python执行系统命令的方法
Python中执行系统命令常见方法有两种: 两者均需 import os (1) os.system # 仅仅在一个子终端运行系统命令,而不能获取命令执行后的返回信息 system(command) ...
随机推荐
- 《Algorithms算法》笔记:优先队列(1)——API和初等实现
1.优先队列的API和初等实现 做一个总结: 栈 :先进后出 队列 :先进先出 随机队列 : 随机出 优先队列:每次出来的是最大值或最小值 1.1优先队列的API 优先队列在很多场合都有用, 比如:在 ...
- 如何虚拟机里安装win7操作系统
不多说,直接上干货! Windows Server 2003.2008.2012系统的安装 关于给电脑换系统,很多人会花钱去电脑店里换,或者是下载Ghost系统.但这些系统都不是微软原版的,制作者已经 ...
- Check类中的incl、union,excl,diff,intersect
定义一些类,这些类之间有父子关系,如下: class Father{} class Son1 extends Father{} class Son2 extends Father{} class To ...
- js二维数组
1.判断是否为二维数组 function isMultiArr(arr){ return arr.every(function(element){ return element instanceof ...
- django项目的生产环境部署,利用nginx+uwsgi
1.坏境准备 centos6.5 django项目 python坏境(python3.6,) 所需的各种模块(django,uwsgi,sqlite3)具体看坏境 我的测试django项目的数据库用的 ...
- protocol buffer开发指南
ProtoBuf 是一套接口描述语言(IDL)和相关工具集(主要是 protoc,基于 C++ 实现),类似 Apache 的 Thrift).用户写好 .proto 描述文件,之后使用 protoc ...
- neo4j 查询
match (p: Node {name:"城关镇"}) return p p 代表的是一个变量,Node为插入neo4j时节点类型,name后面加节点的名称
- freeSWITCH之多平台测试通信
开始测试使用 强烈建议在统一的局域网下进行配置,通信 本机IP:192.168.1.155 架构 freeSWITCH搭建在以Windows平台作为通信服务器.fs_cli为服务器上测试客户端. X- ...
- 安装sublime text2 for ubuntu
Add our Sublime Text 2 Ubuntu PPA using the following commands: sudo add-apt-repository ppa:webu ...
- [有料组每日学习分享计划--00087]32行代码帮你导出IOS酷我音乐下载的无损音乐
需求与研究: 1.IOS的酷我音乐软件,还是不错滴,可以直接下载APE或是320K的MP3音乐,但是我发现PC上的酷我反而没这个功能,而且其他的音乐软件一般只能下载中低品质的音乐.所以能够从IOS中找 ...