How to run a Python Module directly in Ubuntu Terminal? - python

I want to make and launch a command interpreter in Python for Linux. I've used Python's cmd class to run the program.
Currently, I run the program by executing
python main.py (where main.py is the main project file).
I want to be able to run my project by just typing in my project name into the terminal and publish this project on PIP. How do I do that?
EDIT
Im aware that there are multiple examples on the web which demonstrate how to execute a python file directly by filename (adding Python shebang at start of file).
It does answer first half of my question, but I also intend to publish this package on PIP. All tutorials I read on publishing packages on PIP direct me to make python modules which can be run in other python programs, something I dont want. I want to make a python package which can be run directly on

If you package your package with setuptools (which is the most modern way as far as I know), you can just add entry_points to your setup.
Example: You want a script calling the function bar() in the module foo and the script should be called via the terminal with the command bar, then your setup will look like:
setup(
...
entry_points = {
"console_scripts": [
"bar = foo:bar",
],
},
...
)
This is more or less well documented here.

Related

Run a Python made CLI without running the .py file from terminal

When you install Git on your computer, it can be run from the terminal with "git". Similarly, Python can be run with just "python" or "py".
If I make a CLI with argparse and Python, is there a way to have users simply install it and use it in the terminal just by typing
$ myCLI -option
Rather than
$ python path\to\myCLI.py -option
Like all the CLI's I use/interact with do?
Crude Solution
Your script just needs to be somewhere in the user's $PATH (and to have no extension if you don't want them to type myCLI.py). Additionally it needs to start with a magic comment #!/usr/bin/env python3 (If you are running Linux) and be executable (on linux chmod +x myCLI prior to distributing it). Alternatively you create a script in the native shell language of the desired OS (so sh for linux) which calls python3 /path/to/script or python -m module or the like.
If you you name your main script without a .py it prevents you importing it from anything else, so the usual approach is to have an 'entrypoint' script which consists of something like:
#!/usr/bin/env python3
from myApp import main
main()
(see the PyPa docs for a discussion)
Better solution
Of course, you need to deploy your entrypoint script somewhere in the end-user's $PATH. This can be more intersting, but luckily the whole thing is handled by setuptools, and you don't even need to write a script: you just need an entry point function:
Use console_script entry points to register your script interfaces. You can then let the toolchain handle the work of turning these interfaces into actual scripts
official docs
you just put in your setup.py:
setup(
entry_points = {
'console_scripts': [
'PKG_NAME = package.module:func',
],
}
)
and anyone who types PKG_NAME will effectively run package.module:func() (so func is your entrypoint main() function above).
See this question for a discussion of the merits of this approach over the old approach of writing separate scripts for each platform.
Note that if you're not building your app as a python package, but are using some other packaging standard (archlinux PKGBUILD or .deb or whatever) you can still take the same approach---just write the entry point script as above and have the package place it somewhere in the user's $PATH.

How would I allow others to use my script from anywhere in the shell without having to type out the file extension?

Excuse the awkward question wording.
I've made a script. I would like for others to download it from github, and run it by typing programName argument1 argument2, similar to any other popular app used through the terminal such as Jupyter or even opening Atom/Sublime/etc. (ex:jupyter notebook, atom .). However, unlike Jupyter or sublime, my script isn't launching another app, it's a small app meant to be used in the shell.
Currently, to use my script, one must type into the command line python programName.py arg1 etc from within the file's directory.
How do I allow others to dl it and use it from anywhere (not having to be within the directory), without having to type out the whole python programName.py part, and only having to type programName arg1?
This blog post explains step by step how to create a distribution that you can install and it would turn into an executable.
You can refer to this github repo for a sample application.
The full documentation of setuptools is available here.
In general, you should configure your setup.py in order to use the command in the entry-point option:
setup(
name = "your_app_name",
packages = ["package_name"],
entry_points = {
"console_scripts": ['cmd_name = package_name.package_name:main']
},
....
)
This solution would work on every OS where you have installed python.
Your script may need to have an interpreter, "shebang", besides being "reachable" by the $PATH
#!interpreter [optional-arg]
For example, you could have something like
#!/usr/bin/env python
or to force a specific version
#!/usr/local/bin/python2.7
Next, your script needs to be available within the $PATH, check this answer that covers that part: https://unix.stackexchange.com/q/29608/53084
You can simply add your script to PATH variable in order to launch it from anywhere.
In Linux distros, you can simply do it by using a bash command PATH=$PATH:/path/to/your/script.
Make sure you don't have the space around the "=" operator.
Now, the second thing is you don't want your script to be named as pythonProgram.py.You can simply remove the extension .py from PythonProgram.py by adding a single line to the starting of your script.
Open up your script and at the very begining type #!/usr/bin/python.This should be the first line of your code.This line is called shebang and is used to tell the bash which interpreter to be used for compiling the script.
If everything went right, you will be able to run your script as pythonProgram arg1.
In addition to mabe02: Python is a scripting language and usually not compiled, which means you will need an interpreter to run your program.
Programms made in C f.e. can be run on its own because they were compiled into machine code by a compiler.
An interpreter is similar to a compiler as it reads your script and interprets it at runntime. That is why you need to write python before your programm, to tell your computer to interpret your script on runntime, using python. This doesn't mean that there are no possibilities to compile python as can be seen in the other answer and in this link Can a python program be run on a computer without Python? What about C/C++? (py2exe and py2app).

How to execute a script or a funciton through python setuptoos?

I use Distutils to distribute my package, it's very convinient. Now I want to execute a script or a function after the user installed my package through command like pip install mypackage. I thought I could find a API like register(funtionCalledAfterPackageInstalled), just like atexit.register(someFunction), which was often used in python to execute a function before the app exited, but I failed. So I want to ask: is there any elegent way to do such a thing?
Background: I reference a frequently updated dll in my package, and I don't want to put it in my pakcage so I don't need to care about the update. I just want it to be automatically downloaded through a function call after my user install my package. And the environment is WINDOWS, so linux pakcage management tools not work.
After calling setup() in your setup.py file you can call another Python function or method. So you can run python function making what you need or execute external command with subprocess by example.
It will result something like:
from distutil.core import setup
import subprocess
setup( ... stuff ...)
# Call external command
subprocess.Popen('command here', ... attrs ...)
# Or another Python function you wrote
my_function()

Different ways to execute python script

I think I already answered my own question in my mind but in case there are other reasons I don't see, I am wondering what's the benefit/difference between running a python script with
python script.py
and using the shebang
#!/usr/local/bin/python
I usually run my scripts as self executing scripts so I use the shebang. I just came across a team member who runs his programs using
python script.py
My question is which way is better or is this a personal preference thing?
If I run with shebang, I can specify which version I want/need to use. The only problem is I need to make sure that version is installed at that location.
If I run it the other way (not sure what to call it, non-shebang way?), I need to make sure the version I want to use is in my path or defined correctly in my path. I could also type in the full path of python but that can get rather tiring if the path is very long.
Are there other benefits/drawbacks that I don't see? Thanks.
If you want to run your script with shebang, you'll have to make sure that the user running the script has execution rights on the script in question (chmod u+x script.py). That's not the case if you call python with the script as an argument.
Another issue with the shebang solution is that you're forcing the location of the python executable. If I try to run your script and my version of python is in /usr/bin/python instead of /usr/local/bin/python, I'll have to edit your script. On other platforms, such as Windows, I'll have to edit it too.
With the shebang the script must be located on a volume that permits execution, must be allowed to execute by any security modules, and the interpreter specified in the shebang must be present.
Invoking the interpreter directly only requires the script to be readable.
In general environment they are the same.
However, shebang gives you an extra benefit that you can replace your executable very easily without changing any other files just by substituting the file. The second(better) implementation can potentially be anything. For a script based environment, I always use shebang, with a fixture of languages.
for the shebang line, the argument that you need to be concerned about the location of python binary is not valid. you can always write:
#!/usr/bin/env python
to have local environment to decide for you.
If you are treating python as scripting language that one might execute from a POSIX compliant shell then it really doesn't matter.
That said, given that Python is more or less becoming standardized with its package management and installation, I would argue none of the above. What should be done is that all scripts be turned into callables (either functions or callable class instances) that live within modules (preferably defined a namespace package). That callable is the entry point to your program/script. Then a setuptools compliant setup.py should be placed in the root directory of the project for this module and define that as the entry point to your program.
An example:
In example.package/example/package/script.py:
def main():
print('hello world')
The setup.py:
from setuptools import setup, find_packages
setup(
name='example.package',
description='An example package with an entry point',
...
entry_points="""
# -*- Entry points: -*-
[console_scripts]
script = example.package.script:main
""",
)
Note that the script is defined to be example.package.script:main, where the element before the : corresponds to the package and the second element is the callable. In this case, it corresponds to the main function in example/package/script.py (standard python module layout).
Installing the package (preferably in a virtualenv) will generate the correct "executable" that will be immediately accessible from the shell, across all operating systems (i.e. on Windows, a script.exe will be created that basically will start Python with the script).

How transform a python program .py in an executable program in Ubuntu? [duplicate]

This question already has answers here:
What do I use on linux to make a python program executable
(8 answers)
Closed 7 years ago.
I have a simple python program and I want an executable version (for Ubuntu Linux) of this program to avoid running it in the terminal with python myprogram.py.
How can I do that ?
There is no need to. You can mark the file as executable using
chmod +x filename
Make sure it has a shebang line in the first line:
#!/usr/bin/env python
And your linux should be able to understand that this file must be interpreted with python. It can then be 'executed' as
./myprogram.py
As various others have already pointed out you can add the shebang to the top of your file
#!/usr/bin/python or #!/usr/bin/env python
and add execution permissions chmod +x program.py
allowing you to run your module with ./program.py
Another option is to install it the pythonic way with setuptools. Create yourself a setup.py and put this in it:
from setuptools import setup
setup(
name = 'Program',
version = '0.1',
description = 'An example of an installable program',
author = 'ghickman',
url = '',
license = 'MIT',
packages = ['program'],
entry_points = {'console_scripts': ['prog = program.program',],},
)
This assumes you've got a package called program and within that, a file called program.py with a method called main(). To install this way run setup.py like this
python setup.py install
This will install it to your platforms site-packages directory and create a console script called prog. You can then run prog from your terminal.
A good resource for more information on setup.py is this site: http://mxm-mad-science.blogspot.com/2008/02/python-eggs-simple-introduction.html
You can try using a module like cxfreeze
At the top op your python program add:
#!/usr/bin/python
I know the easiest, exact and the best solution. I had the same problem like you but now, I can run my Python/Tkinter(GUI) program with its icon.
As we create .bat files on Windows, we can also create equivalent the .bat files easily in Linux too. Thanks to this file, that, we can start our programs without terminal even if it needs to get command on terminal to start (like Python programs) with double click to its icon (really .png icon :) ) or we can write commands to facilitate our works.
So, how is this going to happen ?
For example, if we want to run our .py program, we just need to write this command to terminal :
python3 locationOfPyFile
So if we create a file that can automatically run this command, problem would be solved. In addition to that, you can have your own icon and even you don't have to open terminal !
Check this article : Run Commands From It's Icon (Easiest Way)

Categories