为了账号安全,请及时绑定邮箱和手机立即绑定

使用python运行Windows Shell命令

使用python运行Windows Shell命令

森栏 2019-10-09 15:31:19
我们如何使用Python与OS Shell交互?我想通过python运行Windows cmd命令。如何实现?
查看完整描述

3 回答

?
繁星淼淼

TA贡献1775条经验 获得超11个赞

您将使用os模块系统方法。


您只需要以命令的字符串形式输入,返回值就是Windows Enrivonment变量COMSPEC。


例如:


os.system('python')打开Windows命令提示符并运行python解释器


查看完整回答
反对 回复 2019-10-09
?
慕村9548890

TA贡献1884条经验 获得超4个赞

重构@ srini-beerge的答案,获取输出和返回码


import subprocess

def run_win_cmd(cmd):

    result = []

    process = subprocess.Popen(cmd,

                               shell=True,

                               stdout=subprocess.PIPE,

                               stderr=subprocess.PIPE)

    for line in process.stdout:

        result.append(line)

    errcode = process.returncode

    for line in result:

        print(line)

    if errcode is not None:

        raise Exception('cmd %s failed, see above for details', cmd)


查看完整回答
反对 回复 2019-10-09
  • 3 回答
  • 0 关注
  • 783 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信