Python scripts in /usr/bin - python

I'm writing a pretty basic application in python (it's only one file at the moment). My question is how do I get it so the python script is able to be run in /usr/bin without the .py extension?
For example, instead of running
python htswap.py args
from the directory where it currently is, I want to be able to cd to any directory and do
htswap args
Thanks in advance!

Simply strip off the .py extension by renaming the file. Then, you have to put the following line at the top of your file:
#!/usr/bin/env python
env is a little program that sets up the environment so that the right python interpreter is executed.
You also have to make your file executable, with the command
chmod a+x htswap
And dump it into /usr/local/bin. This is cleaner than /usr/bin, because the contents of that directory are usually managed by the operating system.

The first line of the file should be
#!/usr/bin/env python
You should remove the .py extension, and make the file executable, using
chmod ugo+x htswap
EDIT: Thomas points out correctly that such scripts should be placed in /usr/local/bin rather than in /usr/bin. Please upvote his answer (at the expense of mine, perhaps. Seven upvotes (as we speak) for this kind of stuff is ridiculous)

Shebang?
#!/usr/bin/env python
Put that at the beginning of your file and you're set

add #!/usr/bin/env python to the very top of htswap.py and rename htswap.py to htswap then do a command: chmod +x htswap to make htswap executable.

I see in the official Python tutorials, http://docs.python.org/tutorial/index.html, that
#! /usr/bin/env python
is used just as the answers above suggest. Note that you can also use the following
#!/usr/bin/python
This is the style you'll see for in shell scripts, like bash scripts. For example
#!/bin/bash
Seeing that the official tuts go with the first option that is probably your best bet. Consistency in code is something to strive for!

Related

How to run python script as global command from any terminal instance similar to pip or howdoi command?

Problem to solve
I have a python script called myscript.py in a directory.
To run myscript.py, I have to open terminal in the same directory and do python myscript.py or python path_to_the_py_file
What I want to achieve
I can open a instance of terminal anywhere, anytime and do myscript or myscript arguments -options. By doing this, I should be able to run the script.
I want to implement something like pip command or the howdoi package.
When I enter myscript in terminal I should not get:
myscript: The term 'myscript' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
If you have any confusion please ask in comments. if the title needs improvement, feel free to edit the question.
There seems to be quite a few things in this question.
First, you want to make you file executable.
chmod +x /path/to/your/script.py
Then, since this is an interpreted language, you’ll have to specify the interpreter in a shebang at the top of the file.
#!/usr/bin/env python
OR
#!/usr/bin/env python3
Finally, you’ll have to put it in your PATH environment variable, which can be done in a variety of ways, simplest might be symlink in ~/bin or ~/.local/bin, depending on what you have.
Also, this will make script.py available as an executable, you can rename it or rename its symlink to just script if you don’t want .py.

Make Python Project Into Command Line Tool

I have a python project with multiple files and a cmd.py which uses argparse to parse the arguments, in the other files there are critical functions. What I want to do is: I want to make it so that if in the command line I were to put cmd -p hello.txt it runs that python file.
I was thinking that I could just simply move the cmd.py file to somewhere like /usr/bin/ or some other directory included in the $PATH, however since I have other files which work with my cmd.py, there will be multiple files in my /usr/bin.
Another thing that I could do is to make a symbolic link between the cmd.py and /usr/bin/cmd like this: ln -s /path/to/cmd.py /usr/bin/cmd, but then where do i put the cmd.py? and is this best practice?
Note: I intend for this to work on Linux and MacOS X, not windows
The usual way to do this is to define a set of entry points in setup.py and let the packaging infrastructure do the heavy lifting for you.
setup(
# ...
entry_points = {
'console_scripts': ['cmd = cmd:main'],
}
)
This requires setuptools.
Here is some documentation for this facility: https://python-packaging.readthedocs.io/en/latest/command-line-scripts.html
For one thing I don't recommend installation in /usr/bin as that's where system programs go. /usr/local/bin or another custom directory added to $PATH could be appropriate.
As for getting it to run like a typical program, name it cmd, wherever you put it, as the extension is not necessary, and add this line to the top of the program:
#!/usr/bin/env python
(You may want to specify python3 instead of just python if you want to ensure Python 3.x is used.)
Then it can be made executable with chmod +x <path to your program>. Ensure that you have the necessary privileges to do this (i.e. sudo may be necessary).
You can add a folder to your path.
in .bashrc add following
export PATH=[New_Folder_Path]:$PATH
put the python program in your path_folder created at step 1.
make it executable : chmod u+x [filename]
open a new terminal, and you should be able to call the python program
NOTE: make sure to put the shebang in your python-file : #!/usr/bin/env python3

How do I run code from a different directory with a bash script

I have been putting my code on github, but I've run into an implementation snag. I run the same code on many computers (including a computer that I do not have root access on).
One piece of code (a bash script) calls some python code like:
python somecode.py
The shell will run the correct version of python, but it won't find somecode.py.
What I've tried:
Fail #1: I tried to add both the directory which contains somecode.py and the full path to the file to the PATH; to no avail. [Errno 2] No such file or directory
Fail #2: I can make it work for one computer ONLY if I add the full path to the correct version of python in the top line:
#!/usr/local/cool/python/version/location
However this breaks it running on any other computer.
Fail #3: I can also make it work if I make the bash script say:
python /full/path/to/github/place/somecode.py
but again, this only works for ONE computer because the paths are different for different computers.
What I really want to do: I want to be able to use the same code (both bash script and somecode.py) on multiple computers.
Any suggestions about how to do this properly is welcome. Thanks!
Solution
Added:
#!/usr/bin/env python
To the top of my somecode.py code;
mv somecode.py somecode
chmod +x somecode
Make sure PATH has /full/path/to/directory/with/somecode.
Bash script now says only:
somecode
and it works.
For problem #2 try
#!/usr/bin/env python
though it may find different versions of Python on different machines, but as long as that's not a problem this should fix that particular problem
See this SO question Python deployment and /usr/bin/env portability too. And this post by Alex Martelli re use of this.
If you say python somefile.py then it will take the location of somefile.py as the current directory, not from $PATH. It will take the location of python from $PATH.
If you say somefile.py then it will take the location of somefile.py from $PATH, and the location of python from the #! line of your python script, which can use the PATH if you follow #Levon's suggestion.

How to run a Python script portably without specifying its full path

Is there a portable way to run a python script from a shell without writing its full path?
For example in Linux, I would like while in my home directory
cd ~
to be able to run a python script called run.py that is in say, ~/long/path/to/run.py, but I want to run it by simply typing
python run.py
instead of
python ~/long/path/to/run.py
I would hope for some kind of search path list that contains several directories just like the PATH variable, so that python run.py runs the first run.py it encounters in one of the directories.
I have considered turning run.py into an executable and adding its directory the system PATH variable, but could not find a portable way of making a python script executable.
EDIT
One year later after asking it, I am a bit less noob, and I see that my question was not very clear and did not make much sense, so after a question upvote I'll clarify some things.
1) Portable.
When I asked this I said portable. However what portable means is not clear in this case, and I did not give much emphasis to it.
the platforms: should work on POSIX (Linux, MacOS, etc.) and Windows
this still does not make much sense since windows uses cmd.exe, and POSIX uses sh, so each one could run the commands with a different syntax. So let's say that the most portable thing possible would be to feed the same input to both sh and cmd.exe, running the python script in both cases. In this case, you could run the same command from an ANSI C system function, which uses sh on POSIX and cmd on Windows. ANSI C being one of the few things that is common to Windows and POSIX, the question makes some sense in that case.
2) Executable
Next, the phrase turning run.py into an executable, is not very clear. By that I was talking about the Linux strategy of chmod +x run.py, add a shebang #!/usr/bin/env python, and adding its directory the system add ~/long/path/to/ the PATH enviroment variable. But then this won't work for windows because windows does not support an executable file metadata property like Linux and because /usr/bin/env does not necessarily exist in Windows.
3) Extension
Finally, in my head I was hoping for a solution that does not specify what kind of file run is, so that if someday we decide to make it, say, a perl file, no interfaces would change.
Therefore, writing run.py would be bad because it would specify the filetype; it would be better to be able to write just run
If the directory containing run.py is on the module search path (for example, PYTHONPATH environment variable), you should be able to run it like this:
python -m run
Here is the documentation on the -m command line option:
-m module-name
Searches sys.path for the named module and runs the corresponding .py file as a script.
You can make a python script executable by adding
#!/usr/bin/env python
to the beginning of the file, and making it executable with chmod +x.
Answer after the clarification edit
I prefer the following approach to the one suggested by #F.J. because it does not require users to specify the file type. Please note that this was not specified in the original question, so his answer to the original question was correct.
Lets call the file pytest.py to avoid conflicts with a possible existing run program.
On POSIX (MacOs, linux) do what #Petr said, which is based on what #alberge said:
chmod +x
add shebang #!/usr/bin/env python
create a directory and add it to path. Usual locations on Linux are: ~/bin/ for a single user, /usr/local/bin/ for all users
symlink (cp -s) the file under your PATH with basename pytest instead of pytest.py
On windows:
create a dir and add it to PATH. AFAIK, there is no conventional place for that, so why not C:\bin\ and ~\bin\?
add .PY to the PATHEXT environment variable so that Windows will recognize files with python extension as runnable files without requiring you to type the extension
associate python files with the python.exe interpreter (Windows Explorer > right click > check "Always use the selected program"). There is an option on the python installer that does this for you.
symlink pytest with extension into the dir under PATH (using Link Shell Extension from Windows Explorer or mklink name dest from cmd )
Now system( "pytest" ); should work in both systems ( sh under Linux, cmd under Windows )
Make python file executable (as "alberge" stated above)
Create some directory and put this directory into your PATH variable
In this directory, create links to your python scripts

What is an 'executable form'?

I'm fairly new to programming but I was wondering what 'executable form' meant & how to convert a Python file into an executable form.
I'd guess that whoever wrote that meant to set the executable bit on the file. To do that on most UNIX platforms, you'll need to go into some kind of shell and run this:
chmod +x /full/path/to/file.py
(note that the full path is not actually required — you can use a relative path, too)
If you've done that and the file starts with an appropriate hashbang like:
#!/usr/bin/env python
Then you should be able to run the script very easily:
./file.py
(assuming your working directory is the same as the directory in which file.py is located)
On windows platform, "executable form" means PE files, more specifically, ".exe" files.
Maybe you can use py2exe to convert a py script to an exe file.

Categories