python commands_Windows环境下使用python的commands.getstatusoutput

windows调用系统或其他脚本的,常用的是os.popen,次命令本身并不返回执行后的状态,无法用于后续的判断,故尝试Unix下的commands.getstatusoutput,发现在windows下并不能正常使用,如下:

>>> import commands

>>> status, output = commands.getstatusoutput('dir')

>>>

>>> import commands

>>> print output

'{' 不是内部或外部命令,也不是可运行的程序

或批处理文件。

>>>

>>> status, output = commands.getstatusoutput(dir)

Traceback (most recent call last):

File "", line 1, in

File "C:\Python27\lib\commands.py", line 59, in getstatusoutput

pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')

TypeError: cannot concatenate 'str' and 'builtin_function_or_method' objects

发现commands调用了os.popen,备份原文件,稍作修改,结果如下:

#pipe = os.popen('{ ' + cmd + '; } 2>&1', 'r')

pipe = os.popen(cmd, 'r')

删除原有的commands.pyc,再试下,即可。

>>> import commands

>>>

>>> status, output = commands.getstatusoutput('dir')

>>>

>>> print output

驱动器 C 中的卷是 Win 7 Pro x64

C:\Users\perofu 的目录

2018/10/17 15:08

2018/10/17 15:08

2018/05/25 14:59

2018/11/22 10:45

2018/11/13 10:31

2018/11/22 10:24

2018/10/12 11:28

2018/10/08 09:43

2018/10/17 14:56

2018/11/08 11:06

2018/05/25 14:59

2018/08/03 17:35

2018/11/22 13:55

1 个文件 5 字节

14 个目录 94,719,250,432 可用字节

>>>

>>>

>>> print status

0

>>>

>>> status, output = commands.getstatusoutput('aaaaa')

>>>

>>> print status

1

>>> print output

>>>

仅作为记录。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值