Chinaunix

标题: 关于os.system()一问。 [打印本页]

作者: guotie    时间: 2006-07-18 15:40
标题: 关于os.system()一问。
我怎么得到os.system()命令输出的内容?

例如os.system('ls -l')

谢谢!
作者: guotie    时间: 2006-07-18 16:05
6.8 subprocess -- Subprocess management

http://www.python.org/doc/2.4/lib/module-subprocess.html
作者: MingStar@CU    时间: 2006-07-21 16:56
用commands模块吧

import commands

status, output = commands.getstatusoutput('ls -l')
作者: unixer2i    时间: 2006-07-21 21:46
原帖由 MingStar@CU 于 2006-7-21 16:56 发表
用commands模块吧

import commands

status, output = commands.getstatusoutput('ls -l')


用用commands模块试了下,我的例子如下:

  1. #!d:/apptools/Python/python
  2. # filename useCMD.py
  3. # just list the system command for use in python mode

  4. import commands
  5. status, output = commands.getstatusoutput('cat -A')
复制代码

我的系统是MS XP, python2。4。3。怎么没有显示呀?

作者: MingStar@CU    时间: 2006-07-21 23:29
原帖由 unixer2i 于 2006-7-21 21:46 发表


用用commands模块试了下,我的例子如下:
[code]
#!d:/apptools/Python/python
# filename useCMD.py
# just list the system command for use in python mode

impo ...



原因是commands模块只能在Unix(或Linux)里用~

详见:http://docs.python.org/lib/module-commands.html
作者: MingStar@CU    时间: 2006-07-21 23:49
原帖由 guotie 于 2006-7-18 16:05 发表
6.8 subprocess -- Subprocess management

http://www.python.org/doc/2.4/lib/module-subprocess.html


查了一下,subprocess是打算用来代替os.system, os.popen, commands.* 等~

而楼主想要的结果用subprocess要这样子写:

  1. >>> import subprocess
  2. >>> outPipe = subprocess.Popen(["dir", '/w'], shell=True, stdout=subprocess.PIPE).stdout
  3. >>> output = outPipe.read()
复制代码


不过在Linux里的话,commands.getstatusoutput 就够用了。
作者: guotie    时间: 2006-07-22 19:51
thanks.
作者: unixer2i    时间: 2006-07-22 22:47
原帖由 MingStar@CU 于 2006-7-21 23:29 发表



原因是commands模块只能在Unix(或Linux)里用~

详见:http://docs.python.org/lib/module-commands.html


嗯,又学一招。

作者: ghostwwl    时间: 2006-07-23 08:56
6楼的正确 如果你是要得到结果就用popen() 好像很多基础的教材上都有讲吧

os.popen
Run a shell command and connect to its input or output streams




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2