简体   繁体   English

避免在终端中键入“ python”来打开.py脚本?

[英]Avoid typing “python” in a terminal to open a .py script?

Whilst running python scripts from my linux terminal, I find myself typing in python myfile.py way too much. 从我的linux终端运行python脚本时,我发现自己在python myfile.py输入的方式太多了。 Is there a way on linux (or windows) to execute a python script by just entering in the name of the script, as is possible with bash/sh? 在Linux(或Windows)上,是否可以通过仅输入脚本名称来执行python脚本,就像使用bash / sh一样? like ./script.py ? 喜欢./script.py吗?

At the top of the script, put 在脚本顶部,将

#!/usr/bin/python

or whatever the path to Python is on your computer (the result of which python on Linux). 或您计算机上的Python路径(在Linux上which python的结果)。 This tells the system to run your script using python . 这告诉系统使用python运行脚本。 You'll also need to do chmod +x script.py for it to work. 您还需要执行chmod +x script.py使其正常工作。

Or if you're really lazy, use alias p=python or something. 或者,如果您真的很懒,请使用alias p=python或其他名称。

您将需要chmod 0755 script.py并且作为脚本的第一行有类似

#!/usr/bin/python

The first line of your Python script should be: Python脚本的第一行应为:

#!/usr/bin/env python

or 要么

#!/usr/bin/env python3

Depending on your version, and if Python 3 is your default or not. 取决于您的版本,以及是否默认使用Python 3


Then, set executable bits at the shell (maybe with sudo if needed): 然后,在外壳上设置可执行位(如果需要,可以使用sudo ):

chmod +x my_script_name.py

Note that with the above done, you could rename your Python script 请注意,完成上述操作后,您可以重命名Python脚本

mv my_script_name.py my_script_name

and then execute your Python script just by: 然后只需执行以下操作即可执行Python脚本:

my_script_name

at the shell line. 在壳线处。

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

相关问题 Python脚本打开并写入终端 - Python Script Open and Write into Terminal 在终端中键入“ python”会运行一个python脚本并吐出错误 - Typing 'python' in terminal runs a python script and spits error 在 Python 脚本中打开一个终端并在新打开的终端中执行终端命令 - Open a terminal in Python script and execute terminal commands in that newly opened terminal 我可以创建一个脚本来打开终端并运行.py吗? - Can I make a script to open terminal and run .py? 如何使用一个python脚本打开Powershell终端? - How to open a powershell terminal with one python script? 从 python 脚本打开多个独立终端 - Open multiple independent terminal from a python script 打开终端,运行python脚本并保持打开状态以获取结果? - Open terminal, run python script and keep it open for results? 如何在pycharm终端中自动打开url(不单击打开)http://127.0.0.1:8000 python manage.py runserver - how to automatically open url(not click open) http://127.0.0.1:8000 python manage.py runserver in pycharm terminal 如果运行.py脚本,是否可以打开新终端,修改文件并同时运行它? - if I run a .py script, can I open a new terminal, modify the file and run it also? 在启动时在终端中启动 python 脚本并保持打开 if/when 异常 - launching python script in terminal at boot and keeping open if/when exception
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM