zoukankan      html  css  js  c++  java
  • Python调用shell

      今天学习了Python通过子进程调用shell,感觉教程上讲的过于繁复,有一些根本没用的功能,比如重定向输入输出,这个shell本身就支持,没有必要用Python的api。决定自己总结下。

      其实总的来说只有两种:

      第一种是简单调用,这种情况下父进程会等待子进程执行完成,返回值是退出信息,例子:

    #导入子流程包
    import subprocess
    #简单调用,可以写多个shell语句,用分号隔开,可以把shell端输出的内容重定向到文本以便python读取,r返回0说明运行正常
    r=subprocess.call("cd ../;ls|wc -l >r.txt 2>&1",shell=True)

    第二种是完整调用,使用Popen类,之前的简单调用实际也是用Popen封装的。Popen默认父进程不等待子进程执行完成,但是可以通过参数设置,例子:

    child=subprocess.Popen("ping -c 5 www.baidu.com",shell=True)
    print 'parent process'

    使用Popen时如果想让父进程等待子进程执行完成,可以添加 child.wait()方法。

    下面列出一些其他方法/属性

    child.pid  #子进程pid

    child.poll()  #检查子进程状态

    child.kill()/child.terminate()  #终止子进程

    child.send_signal()  #向子进程发送信号

  • 相关阅读:
    423. Reconstruct Original Digits from English
    400. Nth Digit
    397. Integer Replacement
    396. Rotate Function
    365. Water and Jug Problem
    335. Self Crossing
    319. Bulb Switcher
    线段树-hdu2795 Billboard(贴海报)
    线段树---求逆序数
    线段树——单点替换区间最值
  • 原文地址:https://www.cnblogs.com/sheeva/p/4988013.html
Copyright © 2011-2022 走看看