1

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 user 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

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

you should add that in windows you must install the tee program.
0

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.

3 Comments

I want to print to stdout by default. I can check if there is argument after the script, and if there isn't then write to stdout instead to file, but I was seeking for a way without writing to file from this script if possible. Thanks
@Ghostly why? What's wrong with writing to a file (especially stdout)? That's no different from a plain print.
OK, maybe you are right. I have couple of interacting scripts, and defaulting to stdout was desired in this examples. I'll check if there is argument - if so write to file, and if not I'll use stdout. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.