python执行shell命令

背景:最近项目中需要执行shell命令,虽然不是难点,但是中间也有一点坑,因此特意记录下来。

python执行shell命令有三种方式,分别是

1. os.system("shell command")

2. os.popen("shell command").read()

其中read()是获取执行shell命令的输出

3. subprocess.call(shell command, shell=True)

或者subprocess.Popen(shell command, shell=True) 也可以是subprocess.Popen(shell command, stdout=subprocess.PIPE, shell=True) 

注:有一点需要注意的就是,如果要export 环境变量,就不能用上述方式,因为执行shell是启动一个进程进行执行,执行export 命令,只会作用于当前进程(何况命令执行完,进程也就结束了),对于程序不起作用。需要如下方法

os.environ['LD_LIBRARY_PATH'] = "your path"

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容