zoukankan      html  css  js  c++  java
  • python>基础>001>基本模块使用汇总

    一、python调用linux系统命令模块

    import os

    import commands

    例如,调用系统命令执行ping操作:

    使用commands模块方法:
    >>> import commands >>> result = commands.getstatusoutput('ping -c 2 8.0.0.1') >>> print result (256, 'PING 8.0.0.1 (8.0.0.1) 56(84) bytes of data.\n\n--- 8.0.0.1 ping statistics ---\n2 packets transmitted, 0 received, 100% packet loss, time 999ms\n') >>> result = commands.getstatusoutput('ping -c 2 127.0.0.1') >>> print result (0, 'PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.\n64 bytes from 127.0.0.1: icmp_req=1 ttl=64 time=0.059 ms\n64 bytes from 127.0.0.1: icmp_req=2 ttl=64 time=0.046 ms\n\n--- 127.0.0.1 ping statistics ---\n2 packets transmitted, 2 received, 0% packet loss, time 999ms\nrtt min/avg/max/mdev = 0.046/0.052/0.059/0.009 ms') >>>
    说明:在instance中的0和256表示的是命令执行状态返回码,0表示成功,256表示不成功(不成功的某个具体状态)。0和256后面的表示的是具体的执行返回结果。
    使用os模块方法:
    >>> result_01 = os.system('ping -c 2 127.0.0.1')
    PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
    64 bytes from 127.0.0.1: icmp_req=1 ttl=64 time=0.078 ms
    64 bytes from 127.0.0.1: icmp_req=2 ttl=64 time=0.049 ms

    --- 127.0.0.1 ping statistics ---
    2 packets transmitted, 2 received, 0% packet loss, time 999ms
    rtt min/avg/max/mdev = 0.049/0.063/0.078/0.016 ms
    >>> print result_01
    0
    >>>
    >>> result_01 = os.system('ping -c 2 8.0.0.1')
    PING 8.0.0.1 (8.0.0.1) 56(84) bytes of data.

    --- 8.0.0.1 ping statistics ---
    2 packets transmitted, 0 received, 100% packet loss, time 1007ms

    >>> print result_01
    256
    >>>

    说明:使用os执行后结果赋值给变量,最终发现,赋值后的变量的值只有执行状态返回码而没有具体的执行结果。




    总结:

    使用commands比os效果好,输出结果包含执行状态返回码和具体执行结果,而且在执行过程中不会有其他输出,所有的执行结果都赋值给了变量;

    使用os,不好的地发是有多余的东西输出到屏幕,并且执行结果只有执行状态返回码。

    综述,推荐使用commands。

  • 相关阅读:
    SpringMVC:com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax;
    SpringMVC DELETE,PUT请求报错 添加支持Http的DELETE、PUT请求
    HashMap源码总结
    ArrayList动态扩容大小
    Java中的可选操作
    Java中深拷贝与浅拷贝理解
    String在内存中如何存储
    异常处理—checked exception 和 unchecked exception
    Comparable和Comparator区别
    Scanner类与Readable接口
  • 原文地址:https://www.cnblogs.com/mangguoxiansheng/p/5977021.html
Copyright © 2011-2022 走看看