Return to stdout if no file name specified

I have a script that takes a file name as an argument, which opens it and writes some things.

I use the with statement:

 with open(file_name, 'w') as out_file: ... out_file.write(...) 

Now what if I want to write in sys.stdout if there is no file_name ?

Do I need to wrap all the actions in a function and set the condition earlier?

 if file_name is None: do_everything(sys.stdout) else: with open(file_name, 'w') as out_file: do_everything(out_file) 
+4
source share
5 answers
 from contextlib import contextmanager @contextmanager def file_or_stdout(file_name): if file_name is None: yield sys.stdout else: with open(file_name, 'w') as out_file: yield out_file 

Then you can do

 with file_or_stdout(file_name) as wfile: do_stuff_writing_to(wfile) 
+6
source

How do you handle command line arguments? If you use argparse , you can use the type and default the add_argument parameters to handle this. For example, try something like the following:

 import sys import argparse def main(argv=None): if argv is None: argv=sys.argv[1:] parser = argparse.ArgumentParser() parser.add_argument('infile', nargs='?', type=argparse.FileType('w'), default=sys.stdin) args = parser.parse_args(argv) print args.infile return 0 if __name__=="__main__": sys.exit(main(sys.argv[1:])) 

If the file name is present as an argument, the argpse script will automatically open and close the file, and args.infile will be the handle to this file. Otherwise, args.infile will be just sys.stdin .

+3
source

You can write your own context manager. I will send sample code later if no one else does

+2
source
 if file_name is None: fd = sys.stdout else: fd = open(file_name, 'w') # write to fd if fd != sys.stdout: fd.close(); 
0
source

Using the with ... as construct is useful for automatically closing a file. This means that using it with sys.stdout , as you know, will crash your program because it will try to shut down the stdout system!

This means that something like with open(name, 'w') if name else sys.stdout as: will not work.

This makes me say that there is no easy and pleasant way to write your snippet better ... but there are probably better ways to think about how to build such code!

The main thing is to find out when you need to open (and, more importantly, close) the file handler for file_name when file_name exists.

Personally, I would just drop with .. as and take care to open the file - and, more importantly, close it! - somewhere else. The mileage for this may vary depending on how your software works.

This means that you can simply do:

 out_file = open(file_name, 'w') if file_name else sys.stdout 

and work with out_file in your program.

When you close, do not forget to check if there is a file or not :)

And have you thought about using the logging module? This makes it easy to add different handlers, print to a file, print to stdout ...

0
source

Source: https://habr.com/ru/post/1403035/


All Articles