简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM