windows 如何从python写入windows命令窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5702909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 16:40:39  来源:igfitidea点击:

how to write into a windows command window from python

pythonwindowswindowcommandpython-2.6

提问by henrima

I am using Python 2.6 I'd like to enter instructions into a command windows from python. I just need the right method. However as an indication, I am showing several failed trials. Here are several trials and the error types I get:

我正在使用 Python 2.6 我想从 python 向命令窗口输入指令。我只需要正确的方法。然而,作为指示,我展示了几次失败的试验。这里有几个试验和我得到的错误类型:

first trial

一审

import subprocess
proc = subprocess.Popen('cmd.exe', stdin = subprocess.PIPE, stdout = subprocess.PIPE)
stdout, stderr = subprocess.communicate('cd Documents')
AttributeError: 'module' object has no attribute 'communicate'

Second trial:

二审:

import subprocess
proc = subprocess.Popen('cmd.exe', stdin = subprocess.PIPE, stdout = subprocess.PIPE)
proc.stdin.write("cd Documents")

No error message, however nothing happens. Il i try to open a folder that doesn't exist , I get the same thing. The command window stays empty

没有错误消息,但没有任何反应。我尝试打开一个不存在的文件夹,我得到同样的结果。命令窗口保持空白

Third trial:

三审:

os.system('cd Documents')

Nothing happens , it returns 1, however if i try to open a folder that doesn't exist, it returns 1 too:

什么也没发生,它返回 1,但是如果我尝试打开一个不存在的文件夹,它也会返回 1:

os.system('cd Documentss')

Last trial

最后审判

a=os.popen("C:\system32\cmd.exe",'w')
a.write("cd Documents")
IOError: [Errno 22] Invalid argument

Thanks for your help

谢谢你的帮助

回答by Alex Bliskovsky

Your first trial is correct, except for the fact that you're calling the module instead of your newly instantiated class. You need to use

您的第一次尝试是正确的,除了您调用的是模块而不是新实例化的类。你需要使用

proc.communicate('cd Documents')

proc.communicate('cd Documents')

回答by user6609527

Your third trial:

你的第三次审判:

 os.system('your command')

works. I used and it's ok:

作品。我用过,没问题:

os.system('ipconfig -renew') # Renew all connections windows

Try:

尝试:

os.system('ipconfig -release') # you will disconnect from your network

Then use:

然后使用:

os.system('ipconfig -renew') # network will back