Python调用系统命令的方法?老男孩教育
- 作者:超哥
- 2023-03-06 12:08
- 人已阅读
简介-Python调用系统命令的方法?老男孩教育Python调用系统命令的方法?老男孩教育移动互联网技术的快速发会掉展,为各程怎大行业都提供了发展机遇,在市场的影响之说感下,Python语象转
- Python调用系统命令的方法?老男孩教育
Python调用系统命令的方法?老男孩教育
移动互联网技术的快速发会掉展,为各程怎大行业都提供了发展机遇,在市场的影响之说感下,Python语象转言变得更加火爆,渗透到各大领域人别,现在很多开发工作都会使用到奥奔Python,不过进行Python开发搭生秃建框架的时候,往往需要命令进行操差男作,那么你知道如何用Python调用系统命令吗?老男孩教育为大家的剩介绍一下。 疮女1. os.system() 这个方法直接调用标准C的system()函数,仅仅在一个子终端运行系统冰饮命令,而不能获取执行返回的翁全信息。 >>> import os >>> output = os.system(‘cat /proc/cpuinfo‘) processor : 0 vendor_id : AuthenticAMD cpu family : 21 ... ... >>> 镇苗 output # doesn‘t capture output 0 2. os.popen() 这个方法执行命令并返回执行后的信息对象,是通过一门读个管道文件将结果返回。 >>> output = os.popen(‘cat /proc/cpuinfo‘) >>> output >>> print output.read() processor : 0 vendor_id : AuthenticAMD cpu family : 21 ... ... >>> 3. commands模块 >>> import commands >>> (status, output) = 都提 commands.getstatusoutput(‘cat /proc/cpuinfo‘) >>> print output processor : 0 vendor_id : AuthenticAMD cpu family : 21 ... ... >>> print status 0 注意1:在类unix的系统下使用此方法返回的返回值(status)与脚本或命令执行之后的返回值不等,这是因为调用了有存os.wait()的缘故,具体原因就得去了蔡桥解下系统wait()的实现了。需要静新正确的返回值(status),只需要对返回值进行右移8位操该离作就可以了。 注意2:当执行命令的参数或者返回中包含了中文文字要洗,那么建议使污用subprocess。 4get不. subprocess模块 该模块是一个功能强大的子进程管理模块,是替换os.system, 遭经 os.spawn*等方法的一个模块。 >>> import subprocess >>> subprocess.Popen(["ls", "-l"]) # python2.x doesn‘t capture output >>> subprocess.run(["ls", "-l"]) # python3.x doesn‘t capture output >>> total 68 drwxrwxr-x 3 xl xl 4096 Feb 8 05:00 com drwxr-xr-x 2 xl xl 4096 Jan 21 02:58 Desktop drwxr-xr-x 2 xl xl 4096 Jan 21 02:58 Documents drwxr-xr-x 2 xl xl 4096 Jan 21 07:44 Downloads ... ... >>>
上一篇:国内高端理财的方式有哪些?
下一篇:没有了