how to write into a windows command window from py

2019-06-13 14:52发布

问题:

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

回答1:

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



回答2:

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