python是一门高级编程语言,语法简单,库函数丰富,可以轻松的嵌套其他语言。为了在Python中使用Linux脚本或命令,有以下几种方式:
1.os.system
os.system('ls -l')
2.os.popen
p = os.popen('dir c:','r')
p.read()
p.close()
3.commands
commands.getstatusoutput('ls -l')
4.subprocess
subprocess.call('ls -l',shell=true)
其中subprocess被python文档推荐方法,其他几种可能已经无法使用,从python3开始使用subprocess.run作为核心方法
subprocess的核心方法为:
subprocess.run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=None, check=False, encoding=None, errors=None)
参数如下:
args: 需要执行的shell命令,如果为字符串,需要指定shell=True或者为不带参数的命令,推荐使用序列(如列表);
stdin/stdout/stderr:分别表示该args命令执行时使用的标准输入、输出和标准错误,可以使用文件描述符(fp=open(‘test’)),0,1,2以及subprocess.PIPE等;
encoding/error:文件以文本形式打开时需要按照指定的encoding/error处理;
shell:设置为true以便使用灵活的shell命令,如~,管道,环境变量等;
run方法在底层进程的创建和管理是通过popen类实现的
关于popen,其原型为:
subprocess.Popen(args, bufsize=-1, executable=None, stdin=None, stdout=None, stderr=None, preexec_fn=None, close_fds=True, shell=False, cwd=None, env=None, universal_newlines=False, startupinfo=None, creationflags=0, restore_signals=True, start_new_session=False, pass_fds=(), *, encoding=None, errors=None)
参数简介:
args:同上,shlex.split(str) 可以用来将复杂的字符命令转化为序列
shell:置为True时,args应该为string,所有参数显式的直接传递给shell,需要程序验证args的安全性;为False时python会保证系统的安全,保证命令的安全执行。