import subprocess

用subprocess中的Popen() 方法来得到shell脚本的一些运行结果,并且也可以指定不同的shell内核。
其构造函数为:

class 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)

如果想要通过subprocess库在python中实现shell命令的运行,可以按照如下的方式书写:

# 此处以ls -a这个命令举例:
cmd = "ls -a"
def bash_command(cmd):
    subprocess.Popen(cmd, shell=True, executable='/bin/bash')
bash_command(cmd)

 

执行以上程序就可以得到在Python中运行shell命令的效果,其中的executable参数可以接受不同的shell类型,指定不同的shell来执行传入的cmd,当然,cmd的格式也要符合相应的shell执行类型。

如果是bash则为“/bin/bash“,根据不同的种类选择参数。