首页 > 编程语言 > 详细

python commands包不支持windows环境与如何在windows下使用的简易方法

时间:2015-02-13 18:17:25      阅读:428      评论:0      收藏:0      [点我收藏+]

commands模块不支持windows环境,让我们来看看。

>>> import commands
>>> print commands.getoutput(‘dir‘)
‘{‘ 不是内部或外部命令,也不是可运行的程序
或批处理文件。
>>> 

 查看commands.getoutput的源代码:

def getoutput(cmd):
    """Return output (stdout or stderr) of executing cmd in a shell."""
    return getstatusoutput(cmd)[1]

 这个函数调用的是commands.getstatusoutput()函数,那查看下commands.getstatusoutput的源代码

def getstatusoutput(cmd):
    """Return (status, output) of executing cmd in a shell."""
    import os
    pipe = os.popen({  + cmd + ; } 2>&1, r)
    text = pipe.read()
    sts = pipe.close()
    if sts is None: sts = 0
    if text[-1:] == \n: text = text[:-1]
    return sts, text

从commands.getstatusoutput的代码可以看出,命令运行的时候改变成了‘{ ‘ + cmd + ‘; } 2>&1‘,这是在linux下运行的命令,windows不支持。
所以,commands模块不支持windows环境。

那如何让它支持windows环境呢?

我的建议:

1、新建一个模块,copy commands的内容到其中

2、将getstatusoutput函数下的 ‘{ ‘ + cmd + ‘; } 2>&1‘ 改为cmd

当然getstatushan函数仍然存在问题,如果要使用的话,请参考windows环境进行修改。

 

总结,以上是我的一点心得,如果存在问题,请联系我。

 

python commands包不支持windows环境与如何在windows下使用的简易方法

原文:http://www.cnblogs.com/tangdouguard/p/4290589.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!