开发者

how to write into a windows command window from python

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:

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:

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


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')


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜