python执行linux命令的简单示例

前端之家收集整理的这篇文章主要介绍了python执行linux命令的简单示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
对python执行linux命令的两种方法感兴趣的小伙伴,下面一起跟随编程之家 jb51.cc的小编两巴掌来看看吧!

python执行linux命令有两种方法

在此以Linux常用的ls命令为例:

方法一:使用os模块


shell# python
>> import os
>> os.system('ls -l')

# End www.jb51.cc

执行结果:


drwxr-xr-x   2 root root  4096 2012-03-12 bin
drwxr-xr-x   4 root root  1024 2011-10-31 boot
drwxr-xr-x   6 root root  4096 2011-11-22 data
drwxr-xr-x  12 root root  3620 01-11 16:01 dev
drwxr-xr-x  93 root root 12288 01-17 04:02 etc
drwxr-xr-x  16 root root  4096 10-18 18:53 home
drwxr-xr-x  11 root root  4096 2012-03-12 lib
drwxr-xr-x   8 root root  4096 2012-01-20 lib64
drwx------   2 root root 16384 2011-10-31 lost+found
drwxr-xr-x   2 root root  4096 2010-01-27 media
drwxr-xr-x   2 root root     0 01-11 16:00 misc
drwxr-xr-x   2 root root  4096 2011-12-02 mnt
drwxr-xr-x   2 root root     0 01-11 16:00 net
drwxr-xr-x  12 root root  4096 2011-11-22 new
drwxr-xr-x   2 root root  4096 2010-01-27 opt
dr-xr-xr-x 168 root root     0 01-11 15:59 proc
drwxr-x---   6 root root  4096 11-06 11:30 root
drwxr-xr-x   2 root root 12288 2012-03-31 sbin
drwxr-xr-x   2 root root  4096 2011-10-31 selinux
drwxr-xr-x   2 root root  4096 2010-01-27 srv
drwxr-xr-x  11 root root     0 01-11 15:59 sys
drwxrwxrwt   4 root root 20480 01-18 04:02 tmp
drwxr-xr-x  16 root root  4096 07-25 16:34 usr
drwxr-xr-x  21 root root  4096 2011-11-02 var

# End www.jb51.cc

方法二:使用subprocess模块


shell# python
 
>> import subprocess 
 
>> subprocess.call('ls -l'.split())

# End www.jb51.cc

执行结果是相同的。

ps:开发中最常用的方法是os模块方法

原文链接:https://www.f2er.com/python/527394.html

猜你在找的Python相关文章