How do I execute a python script from the command

2019-04-16 00:42发布

I apologize in advance if my terminology is off, but what I want to do is execute a python script using a custom command. So for example, I want to write a python script that accepts some shell arguments and performs some arbitrary shell commands. We'll call this script random.py. Instead of typing:

> python random.py arguments go here

I would like to be able to type something like:

> random arguments go here

So in other words, I want to get rid of the python command and omit the .py. I realize that I could use an alias but I also want to make this script available for anyone else that wants to use it, and I don't want to ask them to make an alias.

Basically what I'm after is something like meteor js, zurb foundation, or grunt. After I installed meteor I was able to create a new application by going to the shell and typing:

> meteor create --newapplicationname 

Same concept with foundation and grunt. That's the type of functionality I'm after. Any resources on how to do that sort of thing would be greatly appreciated.

2条回答
The star\"
2楼-- · 2019-04-16 01:04

If you use Setuptools for distributing you project, you can use Automatic Script Creation feature. Just put into setup.py script following code:

from setuptools import setup, find_packages
setup(
    name = "Random",
    version = "0.1",
    packages = find_packages(),
    entry_points = {
        'console_scripts': [
            'random = random:main_func',
        ],
    }
)

A shell script "random", which actually runs function "main_func" from module "random", will be available after project installation.

查看更多
劳资没心,怎么记你
3楼-- · 2019-04-16 01:23

What worked for me (Ubuntu) is putting a symbolic link in /usr/local/bin like this,

$> sudo ln -s /path/to/your/python/script/random.py /usr/local/bin/random
$> sudo chmod 755 /usr/local/bin/random

(If you want to automate this step just put these two commands in a bash script). Normally the terminal should now find the script and execute it if you just type

$> random arg1 arg2

Just make sure your python script starts with

#!/usr/bin/python
查看更多
登录 后发表回答