背景:最近项目中需要执行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"