python中os. popen sy

发布时间:2019-08-26 07:16:59编辑:auto阅读(1666)

    python调用Shell脚本或者是调用系统命令,有两种方法:
    os.system(cmd)或os.popen(cmd),前者返回值是脚本的退出状态码,正确会返回0,错误会返回其他数字。
    后者的返回值是脚本执行过程中的输出内容。实际使用时视需求情况而选择。
    popen的返回时一个对象,直接查看,是这样的结果:<open file 'help', mode 'r' at 0x00000000026B2150>
    popen要想查看结果需要这样查看:

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    import os
    
    f = os.popen("ls -l /root", "r")
    print f
    for line in f:
        print line.strip()

    这个返回的结果是:

    [root@abc301 tmp]# python a.py 
    <open file 'ls -l /root', mode 'r' at 0x2b57da0b2738>
    total 432
    -rwxr-xr-x  1 root root 10773 Oct 23  2017 623get.sh
    -rwxr-xr-x  1 root root    11 Mar 12  2018 aa.sh
    -rw-------  1 root root  1960 Nov  2  2016 anaconda-ks.cfg
    -rw-r--r--  1 root root     0 Oct 24  2017 a.out
    drwxr-xr-x  2 root root  4096 Nov  3  2017 awr
    drwxr-xr-x 14 root root  4096 Oct 23  2017 back

    下面是使用system的案例:

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    
    import os
    aaa = os.system("date")
    print aaa

    运行结果:

    [root@tcas301 tmp]# python a.py 
    Tue Mar 19 13:27:41 CST 2019
    0

    参考:https://www.cnblogs.com/yoyoketang/p/9083932.html

关键字

上一篇: Python 之 sqlalchemy查

下一篇: CSS3