2

I want to do an atomic write with Python's print function. I found this answer, already:

How can I do an atomic write to stdout in python?

But this uses sys.stdout.write. I want to be more flexible and use print instead. When I implemented the same code with print, apparently this matters, since my output turned out not to be correct.

lock = Lock()
def synced_out(*inp):
    with lock:
        print(*inp, file=args.out, sep=args.field_seperator)

Apparently it matters that I use print and not sys.stdout.write.

Full code here, if you expect that is not possible and I might be doing something else wrong:

https://termbin.com/s9ox

In the case of corruption the file was sys.stdout, but I was using redirection and send it to file anyway. I want to preserve however the --out flag so that people with less understanding of "> file" can also use it, or if it is used with a pipe, just maintaining this flexibility.

Python 3.5.2
Linux Ubuntu 16.04

Hielke Walinga
  • 2,677
  • 1
  • 17
  • 30
  • "since my output turned out not to be correct" - so, what's the difference between the two outputs? Is it consistent? Also, please provide a [mcve]. – ForceBru Mar 08 '19 at 14:22
  • 1
    Some file-like objects are lazy and don't actually write anything until their internal buffer gets to a certain size. I wonder if this might be a problem in your code -- the actual writing might occur outside of your `lock` block. Does it help if you `.flush()` your file-like object after printing? – Kevin Mar 08 '19 at 14:26
  • you could try adding flush=True to your print arguments – panda-34 Mar 08 '19 at 14:35
  • @panda-34 That seems to do the trick. Thanks a lot. – Hielke Walinga Mar 08 '19 at 15:24

0 Answers0