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 -> 同意使用
    • 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')
原文地址:https://www.cnblogs.com/kongzhagen/p/6761704.html