首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

commands

自2.6版弃用:commands模块已在Python 3中删除。请改用subprocess模块。

commands模块包含包装函数,os.popen()它将系统命令作为字符串并返回由该命令生成的任何输出,以及可选的退出状态。

子流程模块提供了更多强大的工具来生成新流程并检索其结果。 使用子进程模块优于使用命令模块。

注意

在Python 3.x中,getstatus()和两个未公开的函数(mk2arg()和mkarg())已被删除。 此外,getstatusoutput()和getoutput()已移至子流程模块。

commands模块定义了以下功能:

commands.getstatusoutput(cmd)

使用os.popen()在shell中执行字符串cmd并返回2元组(状态,输出)。 cmd实际上是以{cmd; } 2>&1,以便返回的输出将包含输出或错误消息。 尾随的换行符从输出中剥离。 该命令的退出状态可以根据C函数wait()的规则进行解释。

commands.getoutput(cmd)

getstatusoutput(),除了退出状态被忽略,返回值是一个包含命令输出的字符串。

commands.getstatus(file)

以字符串形式返回ls -ld文件的输出。 该函数使用getoutput()函数,并正确地转义参数中的反斜杠和美元符号。

自2.6版弃用:此功能不明显且无用。这个名字在存在时也是误导性的getstatusoutput()

例:

代码语言:javascript
复制
>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x  1 root        13352 Oct 14  1994 /bin/ls'

扩展内容

Module subprocess 管理子过程模块。

扫码关注腾讯云开发者

领取腾讯云代金券