我正在使用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")
没有错误消息,但没有任何反应。我试着打开一个不存在的文件夹,我得到同样的东西。命令窗口保持空白
第三次审判:
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
感谢您的帮助
答案 0 :(得分:2)
您的第一次试用是正确的,除非您正在调用模块而不是新实例化的类。你需要使用
proc.communicate('cd Documents')
答案 1 :(得分:0)
您的第三次试用:
os.system('your command')
的工作原理。我用过,没关系:
os.system('ipconfig -renew') # Renew all connections windows
尝试:
os.system('ipconfig -release') # you will disconnect from your network
然后使用:
os.system('ipconfig -renew') # network will back