[python] 使用subprocess在Python中执行shell脚本

最近的开发过程中需要在Python中执行shell命令,现将学习到的使用方法简单记录下来


主要参考Python官网的subprocess介绍:

https://docs.python.org/3.5/library/subprocess.html


subprocess提供了两种方式调用子进程(我这里调用子进程主要就是执行shell命令):

  • 一种是subprocess的run()方法
  • 另外一种是更底层的Popen接口

官方建议,如果能够满足需求,尽量使用run()方法来实现子进程调用


1. 使用run()方法的基本示例

执行不带任何选项的shell命令:

import subprocess

subprocess.run("ls")

执行带选项和参数的shell命令:

import subprocess

subprocess.run(["ls","-al","/dev"])
2. 使用Popen的基本示例

Popen的使用和run()方法类似

import subprocess

subprocess.Popen(["ls","-al","/dev"])
3. 利用shlex.split()来格式化命令

当需要执行的shell语句比较复杂时,可以用shlex.split()来帮助格式化命令,然后在传递给run()方法或Popen,简单的示例如下:

import subprocess
import shlex

command_line = "ls -al /dev"
args = shlex.split(command_line)
print(args)
subprocess.Popen(args)


猜你喜欢

转载自blog.csdn.net/weixin_42534940/article/details/80824939
今日推荐