I have the canonical shebang at the top of my python scripts.
#!/usr/bin/env python
However, I still often want to export unbuffered output to a log file when I run my scripts, so I end up calling:
$ python -u myscript.py &> myscript.out &
Can I embed the -u option in the shebang like so...
#!/usr/bin/env python -u
and only call:
$ ./myscript.py &> myscript.out &
...to still get the unbuffering? I suspect that won't work, and want to check before trying. Is there something that would accomplish this?
You can have arguments on the shebang line, but most operating systems have a very small limit on the number of arguments. POSIX only requires that one argument be supported, and this is common, including Linux.
Since you're using the /usr/bin/env
command, you're already using up that one argument with python
, so you can't add another argument -u
. If you want to use python -u
, you'll need to hard-code the absolute path to python
instead of using /usr/bin/env
, e.g.
#!/usr/bin/python -u
See this related question: How to use multiple arguments with a shebang (i.e. #!)?
A portable way to do this is to create another executable that embodies your options.
For example, put this file on your path and name it upython
, and make it executable:
#!/usr/bin/env bash
python -u -and -other -options "$@"
... using whatever options you need. Then your myscript.py
script can be like this:
#!/usr/bin/env upython
(... your normal Python code ...)
Torxed suggested doing this via a shell alias. I'd be very surprised if that worked in any version of unix. It doesn't work in the few distributions I just tested. My approach will work in any unix.