简体   繁体   中英

How to create a python program that run calling name instead of name.py from root terminal?

If I have a main.py file in a folder, how can I create a command in my PC that, calling only main from any point in the terminal, makes my main.py file running? Thanks

You should add main.py to your PATH. What happens when you are running, for instance, python is that your terminal looks up the command python in PATH and runs the program that it is pointing to. You could see it as a kind of shortcut to the program Python.

By adding your program to your PATH, you can tell the computer that if you type helloworld in your terminal, the terminal should run /my/path/to/helloworld.py .

I don't know what OS you are on, so here are links for most common OS on how to add a PATH variable.

Windows

Linux

Mac OSX

If you are on Linux or Mac OS X, make sure the program has a valid shebang line such as #! /usr/bin/python #! /usr/bin/python that points to the Python executable you want to run the script with, then enter chmod +x main.py . Finally, rename the script to remove the .py extension.

You can now invoke it (if you're in the same directory) with ./main . If you want to be able to invoke regardless of the directory you're in, add the script's directory to your PATH variable.

Setting the path and variables in Windows 10

  1. Press the Windows key+X to access the Power User Task Menu. In the
    Power User Task Menu, select the System option. In the About window, click the Advanced system settings link under Related settings on the far-right side.

  2. In the System Properties window, click the Advanced tab, then Click the Environment Variables button near the bottom of that tab.

  3. In the Environment Variables window (pictured below),
    highlight the Path variable in the System variables section and click the Edit button.

  4. Add or modify the path lines with the paths you want the computer to access. Each directory path is separated with a semicolon, as shown below.

    C:...\main.py

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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