12

我的 python 脚本顶部有规范的 shebang。

#!/usr/bin/env python

但是,当我运行脚本时,我仍然经常想将无缓冲的输出导出到日志文件,所以我最终调用:

$ python -u myscript.py &> myscript.out &

我可以像这样在shebang中嵌入-u选项吗...

#!/usr/bin/env python -u

并且只调用:

$ ./myscript.py &> myscript.out &

...仍然得到无缓冲?我怀疑这行不通,并想在尝试之前检查一下。有什么东西可以做到这一点吗?

4

3 回答 3

12

您可以在 shebang 行上有参数,但大多数操作系统对参数数量的限制非常小。POSIX 只要求支持一个参数,这很常见,包括 Linux。

由于您正在使用该/usr/bin/env命令,因此您已经使用了该参数python,因此您无法添加另一个参数-u。如果你想使用python -u,你需要硬编码绝对路径python而不是使用/usr/bin/env,例如

#!/usr/bin/python -u

请参阅此相关问题:How to use multiple arguments with a shebang (ie #!)?

于 2013-05-14T17:42:33.990 回答
4

一种可移植的方法是创建另一个体现您的选项的可执行文件。

例如,将此文件放在您的路径上并命名upython,并使其可执行:

#!/usr/bin/env bash
python -u -and -other -options "$@"

...使用您需要的任何选项。那么你的myscript.py脚本可以是这样的:

#!/usr/bin/env upython
(... your normal Python code ...)

Torxed 建议通过 shell 别名来执行此操作。如果这适用于任何版本的unix,我会感到非常惊讶。它在我刚刚测试的几个发行版中不起作用。我的方法适用于任何 Unix。

于 2015-11-21T03:45:39.433 回答
3

env自 coreutils 8.30 以来的新版本中,有-S此选项。引自man env

   The -S option allows specifing multiple parameters in a script.  Running a script named 1.pl containing the follow‐
  ing first line:

         #!/usr/bin/env -S perl -w -T

  Will execute perl -w -T 1.pl .

  Without the '-S' parameter the script will likely fail with:

         /usr/bin/env: 'perl -w -T': No such file or directory
于 2021-04-26T10:58:19.290 回答