有时候我们需要从Python中执行Linux命令,下面就介绍几种方法?
1. os 模块:
1.1 os.system 函数:
system方法会创建子进程运行外部程序,方法只返回外部程序的运行结果。这个方法比较适用于外部程序没有输出结果的情况。
>>> os.system('echo \ "Hello World\"') # 直接使用os.system调用一个echo命令 Hello World 0 >>> os.system("cat /proc/meminfo") MemTotal: 486640 kB MemFree: 301184 kB Buffers: 10304 kB Cached: 58316 kB SwapCached: 0 kB Active: 43748 kB Inactive: 45336 kB Active(anon): 20476 kB Inactive(anon): 520 kB Active(file): 23272 kB Inactive(file): 44816 kB
注意:上面说了,此方法只会外部程序的结果,也就是os.system的结果,所以如果你想接收命令的返回值,接着向下看
1.2 os模块的popen方法
当需要得到外部程序的输出结果时,本方法非常有用,返回一个类文件对象,调用该对象的read()或readlines()方法可以读取输出内容。
>>> print(os.popen('ls -lt').read()) 总用量 98 drwxr-xr-x. 2 root root 4096 5月 19 04:26 opt dr-xr-x---. 3 root root 4096 5月 19 04:26 root drwxr-xr-x. 19 root root 3760 5月 19 04:22 dev drwxr-xr-x. 78 root root 4096 5月 19 04:22 etc drwxrwxrwt. 7 root root 4096 5月 19 04:22 tmp >>> print(os.popen('ls -lt').readlines()) readlines() 是以列表的形式打印出来