I am working with a Python script that accepts an outfile as an argument. It uses open(outfile, "w") to open and write to that file.
A common convention in Linux is to use - (dash) to write to stdout. It is a common convention but not standard nor part of a shell.
Can I pass - as the outfile name so that Pythons open writes to stdout?
No, the standard library open() function does not translate the filename '-' into stdin or stdout. It is just an ordinary filename, so open("-", "w") will write to a file in the current working directory named -.
You have to explicitly test for that value and so return sys.stdin or sys.stdout (depending on what you needed to read from or write to), instead of opening a file.
E.g. the click command-line interface library, which supports using - as a filename on the command line, explicitly tests for a '-' filename in their open_stream() implementation:
if filename == '-':
if any(m in mode for m in ['w', 'a', 'x']):
if 'b' in mode:
return get_binary_stdout(), False
return get_text_stdout(encoding=encoding, errors=errors), False
if 'b' in mode:
return get_binary_stdin(), False
return get_text_stdin(encoding=encoding, errors=errors), False
open() does accept file handles, so you can pass in 0 for standard input, or 1 for standard output:
>>> inp = open(0)
>>> inp
<_io.TextIOWrapper name=0 mode='r' encoding='UTF-8'>
>>> inp.read(1) # read 1 character from stdin, I entered 'a'
a
'a'
>>> outp = open(1, 'w')
>>> outp
<_io.TextIOWrapper name=1 mode='w' encoding='UTF-8'>
>>> outp.write("foo!") # line buffered, no newline written so not visible yet
4
>>> outp.flush() # flush the buffer
foo!>>>
It's depend on how you retrieve commandline arguments. With sys.argv, argparse or OptionParser modules, yes you can. It mean that you can retrieve '-'. But it's up to you to open stdout in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With