how to open a cmd shell in windows and issue commands to that shell using python

前端 未结 2 1457
执笔经年
执笔经年 2020-12-11 13:56

I\'ve tried

import os
os.system(\'cmd.exe\')

great it opens up a cmd shell

but how do I write commands from my python script so tha

2条回答
  •  甜味超标
    2020-12-11 14:17

    import subprocess
    process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
    process.wait()
    print process.returncode
    

    The command variable should be for example: cmd /k. You can also add a stdin=subprocess.PIPE to the Popen argument list and write commands to cmd: subprocess.Popen(command, shell=True, stdout=subprocess.PIPE,stdin=subprocess.PIPE) the final code:

    import subprocess
    process = subprocess.Popen('cmd /k ', shell=True, stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=None)
    process.stdin.write("dir") #passing command
    stdOutput,stdError = process.communicate()
    print stdOutput
    process.stdin.close()
    

    Or alternatively:

    from subprocess import *
    Popen("cmd /k dir")
    

提交回复
热议问题