in a script I use sys.stdout.write()
to output processed data to stdout, which later I use on CLI to redirect stdout to file:
python.exe script.py > file.out
I could not write to file inside python script as redirected file can't be known
My problem is that I use also raw_input()
, as I need u开发者_开发知识库ser to pass certain number before processing starts, but prompt doesn't show as I redirect stdout - i.e. script waits for user input but does not show anything
Can someone give me a tip how to handle this?
TIA
See if this works for you:
#!/usr/bin/python
import sys
import os
# Disable buffering for stdout
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
x = raw_input(">")
print x
Run this as:
python ./test.py | tee ./file.out
Now, you will see your output on console and it will be redirected to the file.out as well.
Take the filename as a command-line argument instead of redirecting stdout. That way, you can print output or use raw_input()
as normal. Example:
import sys
outfile = open(sys.argv[1], 'w')
# write to the outfile
x = raw_input("What's your name?")
outfile.write(x)
Usage:
python myscript.py file.out
This will work on any platform.
精彩评论