bpo-33927: Handle pyton -m json.tool --json-lines infile infile by CharString · Pull Request #29478 · python/cpython (original) (raw)
There is no guarantee that samefile() works as expected for all cases.
For example,
$ ./python.exe x.py | ./python.exe -m json.tool --json-lines - out.jsonl
Traceback (most recent call last):
File "/Users/inada-n/work/python/cpython/Lib/pathlib.py", line 1006, in samefile
other_st = other_path.stat()
^^^^^^^^^^^^^^^^^
AttributeError: 'str' object has no attribute 'stat'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/inada-n/work/python/cpython/Lib/runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/inada-n/work/python/cpython/Lib/runpy.py", line 86, in _run_code
exec(code, run_globals)
^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/inada-n/work/python/cpython/Lib/json/tool.py", line 87, in <module>
main()
^^^^^^
File "/Users/inada-n/work/python/cpython/Lib/json/tool.py", line 73, in main
options.outfile.expanduser().samefile(infile.name)):
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/inada-n/work/python/cpython/Lib/pathlib.py", line 1008, in samefile
other_st = self._accessor.stat(other_path)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
FileNotFoundError: [Errno 2] No such file or directory: '<stdin>'
There may be other cases that samefile()
don't work as your expect.
Additionally, if we don't load the whole file at once, we shouldn't do that even when infile and outfile is same file.
So I think creating a temporary file and rename on success is the right way.