如何从python写入Windows命令窗口 [英] how to write into a windows command window from python

查看:63
本文介绍了如何从python写入Windows命令窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python 2.6
,我想在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:

第一次试验

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

否错误消息,但是什么也没有发生。我尝试打开一个不存在的文件夹,我得到了同样的东西。命令窗口保持空白

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

第三次试用:

os.system('cd Documents')

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

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

最后试用

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

感谢您的帮助

推荐答案

您的第一次试用是正确的,但事实是您正在调用模块而不是新实例化的类。您需要使用

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文档)

这篇关于如何从python写入Windows命令窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆