将python脚本输出到文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3791905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:46:41  来源:igfitidea点击:

Output a python script to text file

python

提问by Bob

I'm using a script that someone else wrote in python. It's executed from the command line with 3 arguments.

我正在使用其他人用 python 编写的脚本。它是从带有 3 个参数的命令行执行的。

example: "python script.py 1111 2222 3333"

示例:“python script.py 1111 2222 3333”

It does it's thing and works perfectly. The results are NOT saved though, and I would really like to pipe the output to a text file. Can I simply use similar dos commands to accomplish this? ie "...333 > output.txt"

它做它的事情并且完美地工作。虽然结果没有保存,但我真的很想将输出通过管道传输到文本文件。我可以简单地使用类似的 dos 命令来完成这个吗?即“...333 > output.txt”

I don't really want to post the script here if possible since it's not really my work.

如果可能的话,我真的不想在这里发布脚本,因为这不是我的工作。

回答by SingleNegationElimination

yes, if you are in a typical unixy shell, that will work exactly as you hope.

是的,如果您在典型的 unixy shell 中,那将完全按照您的希望工作。

If you want to modify the script to write to a file instead of to the stdout, you can read about how to use file()

如果您想修改脚本以写入文件而不是标准输出,您可以阅读有关如何使用 file()

回答by jkerian

That seems to work fine for me in the DOS shell.

这在 DOS shell 中对我来说似乎很好用。

回答by arbn

f = open('/path/to/file','w')
f.write(string, '\n') # ... etc.

Should be simple enough to add something like that to the script, just in case you'd rather not have to use the shell to pipe output each time.

应该足够简单,可以将类似的内容添加到脚本中,以防万一您不想每次都使用 shell 来管道输出。

回答by Alex Martelli

Redirection works fine both in unix-y shells andin Windows' cmd.exe(which I suspect is what you're calling "the DOS window"... unless you're managing to run Python on Windows '95 or something!-).

重定向在 unix-y shellWindows 中都可以正常工作cmd.exe(我怀疑这就是您所说的“DOS 窗口”……除非您设法在 Windows 95 或其他系统上运行 Python!-)。

$ python script.py 1111 2222 3333 >output.txt

where the $is notsomething you type, but rather stands for "whatever prompt your shell / command window is giving you". Just to be totally unambiguous, what you dotype at said prompt to get redirection is just:

其中$不是东西,你打字,而是表示“任何提示你的shell /命令窗口是给你的。” 只是为了完全明确的,你什么请在说提示符下,得到重定向就是:

python script.py 1111 2222 3333 >output.txt

just like what you type now (without redirection) is

就像你现在输入的(没有重定向)是

python script.py 1111 2222 3333