简体   繁体   English

使用shebang调用python脚本

[英]Call a python script with a shebang

I want to run a python script foo.py from the command line like this我想像这样从命令行运行 python 脚本foo.py

$ foo

Using a shebang in foo.py , for example:foo.py使用 shebang,例如:

#!/usr/bin/env python
print('this is foo')

allows me to call it like this:允许我这样称呼它:

$ ./foo.py

How do I drop the leading ./ and the trailing .py ?如何删除前导./和尾随.py

First, rename the file from foo.py to foo .首先,将文件从foo.py重命名为foo

Then, move the file to /usr/local/bin/ or /home/user/.local/bin if the script will only be executed by a single user.然后,如果脚本仅由单个用户执行,则将文件移动到/usr/local/bin//home/user/.local/bin Instead, if your script is placed somewhere in the system for example "/path/to/foo", you could add your "/path/to/foo" to the $PATH variable.相反,如果您的脚本放置在系统中的某个位置,例如“/path/to/foo”,您可以将“/path/to/foo”添加到 $PATH 变量中。

After opening a new terminal session.打开一个新的终端会话后。 You should be able to execute the script without the "./" and ".py".您应该能够在没有“./”和“.py”的情况下执行脚本。

By the way "./" means that you want to execute a file in the current working directory.顺便说一句,“./”表示您要执行当前工作目录中的文件。 It is always possible to execute a file using a full path of the file, for example "/usr/bin/something_to_run".始终可以使用文件的完整路径来执行文件,例如“/usr/bin/something_to_run”。

Please consider reading about PATH variable here .请考虑在此处阅读有关 PATH 变量的信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM