简体   繁体   English

从命令行窗口运行python无法正常工作

[英]run python from command line windows not working

I am trying to run the python script in windows command line. 我正在尝试在Windows命令行中运行python脚本。 Script is executing successfully. 脚本执行成功。 But when i try to redirect the output to file, it is still printing in the console. 但是,当我尝试将输出重定向到文件时,它仍在控制台中打印。

python hello.py -o hello.out

am i doing anything wrong ? 我做错什么了吗?

I think you should be doing this: 我认为您应该这样做:

python hello.py > hello.out

** EDIT ** An additional question was asked about stdin. **编辑**询问了有关stdin的其他问题。

From the command-line you can do something like this: 在命令行中,您可以执行以下操作:

python foo.py < in.txt > out.txt

Inside foo.py you need to make sure you are grabbing stdin from somewhere, so do something like this: foo.py内部,您需要确保从某个地方获取标准输入,因此请执行以下操作:

import fileinput
for line in fileinput.input():
    print(line)
    # do stuff with each line of input

Unless your script supports -o itself, I do not expect that flag to do anything. 除非您的脚本支持-o本身,否则我不希望该标志执行任何操作。 python does not have such an option, and if it did, you would have to put it before the name of your script so that it could be identified as an option to the interpreter instead of your script. python没有这样的选项,如果有,则必须将其放在脚本名称之前,以便可以将其标识为解释器的选项,而不是脚本的选项。

Here is a good article on how to redirect output in Windows: https://support.microsoft.com/en-us/kb/110930 . 这是一篇有关如何在Windows中重定向输出的好文章: https : //support.microsoft.com/zh-cn/kb/110930 Surprisingly, it is done the same was as in Linux, using the > character. 令人惊讶的是,使用>字符完成了与Linux中相同的操作。 Your example should be written as either 您的示例应写为

python hello.py > hello.out

or as 或作为

python hello.py > hello.out 2>&1

if you want to include standard error as well as standard output in your file. 如果要在文件中包括标准错误以及标准输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM