且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不键入“python ..."的情况下运行python脚本

更新时间:2022-03-28 21:21:50

你必须添加shebang:

You've got to add the shebang:

#!/usr/bin/env python

然后使脚本可执行:

chmod +x foo

然后你可以像其他任何可执行文件一样运行它:

Then you can run it like any other executable:

./foo

还有一个来自 Homer6 的说明:如果你从 windows 编辑文件并在 linux 上调用它,你可能会遇到神秘的没有这样的文件或目录"错误.这是由于行的行尾是 CRLF 而不是 LF.如果将它们转换为 LF,脚本将按预期执行.Notepad++ > 查看 > 显示符号 > 显示行尾以显示 EOL 字符.和 Notepad++ > Edit > EOL Conversion > Unix Format 将所有行结尾转换为使用 LF.或者,您可以使用 dos2unix 工具 (dos2unix foo.py),该工具存在于大多数 Linux 系统中.

And a note from Homer6: if you're editing the file from windows and invoking it on linux, you may run into the cryptic "No such file or directory" error. It's due to the line endings of the lines being CRLF instead of LF. If you convert them to LF, the script will execute as expected. Notepad++ > View > Show Symbols > Show End of Line to show the EOL characters. And Notepad++ > Edit > EOL Conversion > Unix Format to convert all line endings to use LF. Alternatively, you can use the dos2unix tool (dos2unix foo.py), which is present on most Linux systems.