如何从Python执行命令提示符命令

64 投票
11 回答
311770 浏览
提问于 2025-04-16 14:44

我试过类似这样的东西,但没有效果:

command = "cmd.exe"
proc = subprocess.Popen(command, stdin = subprocess.PIPE, stdout = subprocess.PIPE)
proc.stdin.write("dir c:\\")

11 个回答

24

试试这个:

import os

os.popen("Your command here")
99

这样做怎么样:

import os
os.system('dir c:\\')
43

你可能想试试这样做:

command = "cmd.exe /C dir C:\\"

我觉得你不能直接把数据传给 cmd.exe... 如果你是从Unix系统过来的话,嗯,cmd.exe确实有些不太好用的地方!

补充:根据Sven Marnach的说法,你可以把数据传给 cmd.exe。我在Python的环境里试了以下代码:

>>> import subprocess
>>> proc = subprocess.Popen('cmd.exe', stdin = subprocess.PIPE, stdout = subprocess.PIPE)
>>> stdout, stderr = proc.communicate('dir c:\\')
>>> stdout
'Microsoft Windows [Version 6.1.7600]\r\nCopyright (c) 2009 Microsoft Corporatio
n.  All rights reserved.\r\n\r\nC:\\Python25>More? '

如你所见,你还需要做一些工作(只有第一行的结果会返回),但你可能能让这个工作起来...

撰写回答