如何从Python写入Windows命令窗口
我正在使用Python 2.6 我想从 python 将指令输入命令窗口。 我只需要正确的方法。然而,作为一个指示,我展示了几次失败的试验。 以下是我得到的几次试验和错误类型:
第一次试验
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'
第二次试验:
import subprocess
proc = subprocess.Popen('cmd.exe', stdin = subprocess.PIPE, stdout = subprocess.PIPE)
proc.stdin.write("cd Documents")
没有错误消息,但没有任何反应。 Il 我尝试打开一个不存在的文件夹,我得到了同样的结果。命令窗口保持为空
第三次试验:
os.system('cd Documents')
没有任何反应,它返回 1,但是如果我尝试打开一个不存在的文件夹,它也会返回 1:
os.system('cd Documentss')
最后一次试验
a=os.popen("C:\\system32\\cmd.exe",'w')
a.write("cd Documents")
IOError: [Errno 22] Invalid argument
感谢您的帮助
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的第一次试验是正确的,除了您正在调用模块而不是新实例化的类这一事实。您需要使用
proc.communicate('cd Documents')
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:
works. I used and it's ok:
Try:
Then use: