[英]Windows file redirection not working from within python script
The following line of python code opens a new windows cmd prompt and executes the ipconfig command but fails to redirect the output to a file I give it. 以下python代码行将打开一个新的Windows cmd提示符并执行ipconfig命令,但无法将输出重定向到我提供的文件中。
os.system("start cmd /k ipconfig > {file_name}")
If I do the same command directly into a cmd prompt, it has no problem with the redirection. 如果我直接在cmd提示符下执行相同的命令,则重定向没有问题。 Any idea why this might fail?
知道为什么这可能会失败吗?
If I type this command at a command prompt 如果我在命令提示符下键入此命令
start cmd /k ipconfig > {file_name}
it doesn't redirect the output from ipconfig
. 它不会重定向
ipconfig
的输出。 It opens a new console and in that console it runs ipconfig
, sending output to the screen. 它打开一个新控制台,并在该控制台中运行
ipconfig
,将输出发送到屏幕。 start
produces no output of its own, so the >
redirects non-existent output from start
to {filename}
and creates a zero-byte output file. start
产生自己的输出,因此>
将不存在的输出从start
重定向到{filename}
并创建一个零字节的输出文件。
To do the redirection using start
you need to associate the >
with ipconfig
like this: 要使用
start
进行重定向,您需要将>
与ipconfig
关联,如下所示:
start cmd /k "ipconfig > {file_name}"
But if you're planning to invoke a shell from a Python program, it's usually not handy to open a console window and leave it there. 但是,如果您打算从Python程序中调用Shell,通常不方便打开控制台窗口并将其保留在其中。 If I type this simpler command at the command prompt
如果我在命令提示符下键入此简单命令
ipconfig > {file_name}
it works as you describe. 正如您所描述的那样工作。 Likewise,
同样,
os.system(r"ipconfig > C:\users\.blah.\{file_name}")
will work in Python, but you need to specify the path of the output file, because otherwise os.system()
will probably try to send the file to a default location that you're not permitted to write to (because it is a subfolder of Program Files
). 可以在Python中运行,但是您需要指定输出文件的路径,因为否则
os.system()
可能会尝试将文件发送到不允许写入的默认位置(因为它是子文件夹) Program Files
)。 Use an r
-string so that you don't have the hassle of doubling backslashes. 使用
r
-string,这样就不会使反斜杠加倍。
And consider using the subprocess
module in preference to os.system
. 并且考虑优先于
os.system
使用subprocess
模块。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.