这篇文章给大家分享的是有关Python执行外部命令的方法的内容。小编觉得挺实用的,因此分享给大家做个参考。一起跟随小编过来看看吧。

调用shell命令

#!/usr/bin/python3importsubprocess#执行外部命令'date'subprocess.call('date')#传递选项和参数给命令print("\nTodayis",end="",flush=True)subprocess.call(['date','-u','+%A'])#其他例子print("\nSearchingfor'helloworld'",flush=True)subprocess.call(['grep','-i','helloworld','hello_world.py'])

这里的import语句用于载入subprocess模块,它是Python标准库的一部分

subprocess模块中的call函数是一种执行外部命令的方式

通过传递True给flush参数(默认是False),我们确保这个信息在subprocess.call运行之前输出

想要给命令传递参数,需要使用字符串列表

$./calling_shell_commands.pyTueJun2118:35:33IST2016TodayisTuesdaySearchingfor'helloworld'print("HelloWorld")

使用扩展调用shell命令

#!/usr/bin/python3importsubprocess#不使用扩展调用Shell命令print("Noshellexpansionwhenshell=False",flush=True)subprocess.call(['echo','Hello$USER'])#使用Shell扩展调用Shell命令print("\nshellexpansionwhenshell=True",flush=True)subprocess.call('echoHello$USER',shell=True)#如果引号是命令的一部分则进行反义print("\nSearchingfor'helloworld'",flush=True)subprocess.call('grep-i\'helloworld\'hello_world.py',shell=True)

默认subprocess.call不会扩展shell 通配符,使用 command替换等等

可以设定shell参数为True进行重写

注意现在整个命令行都作为一个字符串而不是字符串列表

命令中含有引号如要转义

仅在你确定命令会正确执行的情况下使用shell=True,否则会存在安全问题

$./shell_expansion.pyNoshellexpansionwhenshell=FalseHello$USERshellexpansionwhenshell=TrueHellolearnbyexampleSearchingfor'helloworld'print("HelloWorld")

在特定情况下,我们可以使用单/双引号的组合来避免使用转义符号

#像这样使用另一种引号subprocess.call('grep-i"helloworld"hello_world.py',shell=True)#或者这样subprocess.call("grep-i'helloworld'hello_world.py",shell=True)

Shell命令重定向可以正常使用

#为了避免call函数字符串太常,我们使用变量先存储命令cmd="grep-h'test'report.logtest_list.txt>grep_test.txt"subprocess.call(cmd,shell=True)

避开使用shell=True

>>>importsubprocess,os>>>subprocess.call(['echo','Hello',os.environ.get("USER")])Hellolearnbyexample0

os.environ.get("USER")返回环境变量USER的值

0退出状态码,意味着成功执行了命令。

获取命令输出和重定向

#!/usr/bin/python3importsubprocess#输出也包含任何的错误信息print("Gettingoutputof'pwd'command",flush=True)curr_working_dir=subprocess.getoutput('pwd')print(curr_working_dir)#获取命令执行的状态和输出#退出状态码不是“0”意味着有什么事情出错了ls_command='lshello_world.pyxyz.py'print("\nCallingcommand'{}'".format(ls_command),flush=True)(ls_status,ls_output)=subprocess.getstatusoutput(ls_command)print("status:{}\noutput:'{}'".format(ls_status,ls_output))#抑制出错信息#subprocess.call()返回命令的状态码returnsstatusofcommandwhichcanbeusedinsteadprint("\nCallingcommandwitherrormsgsuppressed",flush=True)ls_status=subprocess.call(ls_command,shell=True,stderr=subprocess.DEVNULL)print("status:{}".format(ls_status))

getstatusoutput()的输出是元组数据类型,更多信息和例子在后续章节

getstatusoutput()和getoutput()老式的函数

使用有更多特性和安全选项的新函数

$./shell_command_output_redirections.pyGettingoutputof'pwd'command/home/learnbyexample/Python/python_programsCallingcommand'lshello_world.pyxyz.py'status:2output:'ls:cannotaccessxyz.py:Nosuchfileordirectoryhello_world.py'Callingcommandwitherrormsgsuppressedhello_world.pystatus:2

感谢各位的阅读!关于Python执行外部命令的方法就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到吧!