Python modules : os, subprocess and commands

1. What’s the difference between all of the os.popen() methods?

 

popen2 doesn't capture standard error, popen3 does capture standard error and gives a unique file handle for it. Finally, popen4 captures standard error but includes it in the same file object as standard output.

  • os.popen()   -> stdout
  • os.popen2() -> (stdin, stdout)
  • os.popen3() -> (stdin, stdout, stderr)
  • os.popen4() -> (stdin, stdout_and_stderr)

2. os.popen() vs os.system()

From what I've deciphered, the only differences between os.popen() and os.system() are
a) popen automatically starts a new process while system only does it if you include an &
b) popen hooks onto stdout and stdin.
If so, what's the use of os.system()???

 

a) is not true. Under Unix both start a new process.

The important difference (as I understand it) is popen lets you interact with the program by reading and writing pipes while it's running. system() is more of a batch mode thing, the program runs to completion, then you get the return status.

>??? If so, what's the use of os.system()?
If you just want to run a shell command and don't need to provide any stdin and don't care about stdout/stderr.
For example, if you just want to copy a directory tree from one place to another:
status = os.system("cp -r srcdir /some/where/else")
If you want to start a program, send it input and/or watch its output as it runs, then use popen().
os.system is a standard call to the C standard function call system().
It doesn't allow you to catch the output of the program like os.popendoes.
os.popen is piped open so that you can capture in your python scripts what the program outputs.
os.system simply calls the outside program and sends it's contents to stdout which can be
redirected to a file in your shell.
Call os.system if your python program doesn't need to capture anything from your outside program.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值