python how to run python without specifying the interpreter - python

when you run a python script, you have to do
python3 filename
Is there something you can write in the python file to make it so that you dont have to say python3 before running it. I tried the #!/ line, but when I do:
./filename
it says permission denied. Is specifying the interpreter name when running the program mandatory?

At the top of your python file, you'll want to add the path to the Python3 binary. This is commonly referred to as a "hashbang" or "shebang". It tells your shell how to interpret or run your file (without it, if you tried ./<python-file>, it would try to interpret it as bash.
#!/path/to/python3
On my computer, it's
#!/usr/bin/python3
To determine the path where your python3 binary (or link) is located, run
$ which python3
Alternatively, it's better to use env, as it will ensure the interpreter used is the first one on your environment's $PATH.
#!/usr/bin/env python3
Note, you'll need to run
$ chmod a+x <python-file>
to change the mode to make it executable. The a tells it to make it executable for all (user, group, and others), so if you do not want this, you can leave it out (as in, chmod +x <python-file>).
To not have to run ./ before the executable, you'll want to set your PATH as
export PATH=$PATH:.
in your .bashrc or similar *rc file for your shell. (export makes the variable available to sub-processes.) Then you'll want to run
$ source ~/.bashrc

I'm guessing you are on a linux or unix bases operating system. Yes there is something you can do. Hopefully you are using the import os and import sys library for any interaction with terminal. Next you have to do a chmod command on the file to make it executable
The command would be
chmod +x [python_file.py]
or usually (if not root)
sudo chmod +x [python_file.py]

Related

How you use virtualenv within python script, so we need not to activate it everytime

Currently I'm running this command in terminal:
source /home/protected/env/bin/activate
And then I run this and it works:
python3 /home/protected/ethereum-wallet-generator.py
But it seems like it should be required to enter source /home/protected/env/bin/activate first. Is it not possible to specify the path somewhere within the python script or at least a way to turn this into a one-liner instead of having to send 2 separate commands?
Yes, it is possible. You can just change the shebang to this
#!/home/protected/env/bin/python
Then you invoke the script like so (this is your one-liner)
/home/protected/ethereum-wallet-generator.py
Note that it needs to be executable, you can change it like this
chmod u+x /home/protected/ethereum-wallet-generator.py
If you invoke the python interpreter inside the Virtual Environment, it will act as if the activate script was first sourced. Note that you don't even need to specify "python3", but can just go "python"

Is there a single line way to run a command in a Python venv?

I have a command that only runs correctly inside a Python virtual environment I've configured (as intended). I know that I can run the command as
$ cmd args
once I've activated the venv. But (due to the constraints of the tool I'm using) I need to activate run (and deactivate?) in one line: something equivalent to running
$ activate_somehow cmd args
outside the command line.
Is there a way to do this?
You can generally run something in a virtual environment simply by using a fully qualified path to the script. For example, if I have:
virtualenv .venv
Then I can install something into that virtual environment without activating it by running:
.venv/bin/pip install foo
This should be true for anything installed using standard Python mechanisms.
After looking into the generated bin/activate script, it seems like the only thing relevant to python is the VIRTUAL_ENV variable, so this should be enough to get going:
$ env VIRTUAL_ENV=path/to/venv python ...
Note that the python executable in the bin directory of target environment is just a symlink to globally installed interpreter, which does nothing other that setting process executable path. Assuming the program does not make use of it, utilizing the main binary itself seems harmless. In case you have installed a package which in turn installs some executables, just specify the absolute path:
$ env VIRTUAL_ENV=path/to/venv path/to/venv/bin/executable
You can create a simple wrapper script which runs activate, executes your command, and then deactivates simply by exiting the script in which your environment was activated.
#!/bin/sh
. ${venv-./env}/bin/activate
"$#"
This lets you set the environment variable venv to the path of the environment you want to use, or else uses ./env if it is unset. Perhaps a better design would be to pass the env as the first parameter:
#!/bin/sh
. "$1"/bin/activate
shift
"$#"
Either way, save this somewhere in your PATH ($HOME/bin is a common choice for your private scripts) and give it executable permission.
I found venv-run which should do what you ask:
pip install venv-run
venv-run cmd args
Larsk's answer is probably cleaner, but this is another possible way.
Assuming you use UNIX and your user is user and you have a virtual environment in home (any) directory, ie /home/user/venv, you can make a script like:
#!/bin/sh
export VIRTUAL_ENV=/home/user/venv
export PATH=/home/user/venv/bin:$PATH
python3 "$#"
We can make this script executable (eg call it venv-python3 and do chmod +x venv-python3) and call it as such, or put it some place discoverable in PATH - let's say alongside python. Assuming you have sudo rights:
sudo cp venv-python3 /usr/bin/venv-python3
Then we can call that instead of the python callable. Since the variables are set within the script, explicit call on deactivate is not necessary at exit.
Example:
user#machine ~ % venv-python3 --help
This works for at least for virtualenv version 20.0.17 but if adopted, you should be keeping an eye on what variables bin/activate sets, if this ever changes.
Yes, you can execute the python file using a virtual environment in a single line of command on windows.
venv\Scripts\activate&&python fall_detector.py
I installed pgadmin4 in my home directory in a virtual environment called "pgadmin4".
I use fish shell and it runs perfectly fine with:
~/pgadmin4/bin/python3 ~/pgadmin4/lib/python3.10/site-packages/pgadmin4/pgAdmin4.py
Just in case this helps somebody.

How to make the Shebang be able to choose the correct Python interpreter between python3 and python3.5

I'm developing a set of script in python3, as shebang I use this:
#!/usr/bin/env python3
Everything goes ok, but in some virtual machines where are executed the name of interpreter is python3.5. I will like to be able to execute my scripts in both enviroment but I can't change the filesystem of virtual machine (so I discard solutions like make a link from python3.5 to python3 )
I look at man of env but I don't find any way to specify a searching pattern or something like that.
I try to set an alias at begining of my sessions pointing to right python interpreter but env don't use it.
My unique solution is call my scripts saying which interpreter must use but is very anoying:
python3.5 myscript.py
Any idea is welcome!, thanks!
No need to bring in separate shell and python scripts, a single file can be both!
Replace your shebang line with this sequence:
#!/bin/sh
# Shell commands follow
# Next line is bilingual: it starts a comment in Python, and is a no-op in shell
""":"
# Find a suitable python interpreter (adapt for your specific needs)
for cmd in python3.5 python3 /opt/myspecialpython/bin/python3.5.99 ; do
command -v > /dev/null $cmd && exec $cmd $0 "$#"
done
echo "OMG Python not found, exiting!!!!!11!!eleven" >2
exit 2
":"""
# Previous line is bilingual: it ends a comment in Python, and is a no-op in shell
# Shell commands end here
# Python script follows (example commands shown)
import sys
print ("running Python!")
print (sys.argv)
If you can install scripts, you can also install a wrapper called python3.5 which simply dispatches python3.
#!/bin/sh
exec env python3 "$#"
You'll obviously need to chmod a+x this script just like the others you install.
You'll have to add the script's directory to your PATH after the system python3.5 directory to avoid having this go into an endless loop, and only use this script as a fallback when the system doesn't already provide python3.5.
As you noted, env doesn't know or care about your personal shell aliases or functions, and doesn't provide for any dynamic calculation of the binary to run by itself; but you have the shell at your disposal (and Python of course, once you find it!) -- it simply uses the PATH so if you can install your other scripts in a directory which is in your PATH (which must be the case for the #!/usr/bin/env shebang to make sense in the first place) you can store this script there, too.
As noted in comments, it's weird and user-hostile to only install python3.5 and not at least optionally make python3 a symlink to it, so perhaps you could eventually persuade whoever maintains the image you are installing into to provide this.
You could create a shell script that uses python 3.5 if it is installed, otherwise uses python 3 and executes your script with the correct version.
No need for python shebang.
In your shell script you may test if which python3.5 returns something; if it does, then python3.5 is installed, otherwise you'd have to use python3

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. 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? like ./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). This tells the system to run your script using python. You'll also need to do chmod +x script.py for it to work.
Or if you're really lazy, use alias p=python or something.
you will need to chmod 0755 script.py and as a first line in script have something like
#!/usr/bin/python
The first line of your Python script should be:
#!/usr/bin/env python
or
#!/usr/bin/env python3
Depending on your version, and if Python 3 is your default or not.
Then, set executable bits at the shell (maybe with sudo if needed):
chmod +x my_script_name.py
Note that with the above done, you could rename your Python script
mv my_script_name.py my_script_name
and then execute your Python script just by:
my_script_name
at the shell line.

How to execute python file in linux

I am using linux mint, and to run a python file I have to type in the terminal: python [file path], so is there way to make the file executable, and make it run the python command automatically when I doublr click it?
And since I stopped dealing with windows ages ago, I wonder if the .py files there are also automatically executable or do I need some steps.
Thanks
You have to add a shebang. A shebang is the first line of the file. Its what the system is looking for in order to execute a file.
It should look like that :
#!/usr/bin/env python
or the real path
#!/usr/bin/python
You should also check the file have the right to be execute. chmod +x file.py
As Fabian said, take a look to Wikipedia : Wikipedia - Shebang (en)
I suggest that you add
#!/usr/bin/env python
instead of #!/usr/bin/python at the top of the file. The reason for this is that the python installation may be in different folders in different distros or different computers. By using env you make sure that the system finds python and delegates the script's execution to it.
As said before to make the script executable, something like:
chmod u+x name_of_script.py
should do.
yes there is. add
#!/usr/bin/env python
to the beginning of the file and do
chmod u+rx <file>
assuming your user owns the file, otherwise maybe adjust the group or world permissions.
.py files under windows are associated with python as the program to run when opening them just like MS word is run when opening a .docx for example.
1.save your file name as hey.py with the below given hello world script
#! /usr/bin/python
print('Hello, world!')
2.open the terminal in that directory
$ python hey.py
or if you are using python3 then
$ python3 hey.py
Add to top of the code,
#!/usr/bin/python
Then, run the following command on the terminal,
chmod +x yourScriptFile
Add this at the top of your file:
#!/usr/bin/python
This is a shebang. You can read more about it on Wikipedia.
After that, you must make the file executable via
chmod +x your_script.py
If you have python 3 installed then add this line to the top of the file:
#!/usr/bin/env python3
You should also check the file have the right to be execute. chmod +x file.py
For more details, follow the official forum:
https://askubuntu.com/questions/761365/how-to-run-a-python-program-directly

Categories

Resources