Run Python code without using python name.py and ./name [duplicate] - python

This question already has answers here:
how to run python script without typing 'python ...'
(5 answers)
Closed 2 years ago.
I have a basic problem where I don't know how to run a Python script from command line in Ubuntu without using python keyword. So, I put a shebang in my Python script so I could run it as nameofthescript from the command line, but I only could do it by using ./nameofthescript. I want to be able to run it by just typing the name of the script in the cmd. I searched and tried everything I could on the web, but none is working. Any help is appreciated. Below is a simple code I wrote to test it.
I already tried chmod +x this file. Also this file is saved with no extension.
#!/usr/bin/python
import sys
def main(argv):
print(argv)
print("Hello")
if __name__ == "__main__":
main(sys.argv[1:])

The problem is with your $PATH variable.
When you go to run a command (without the "./" in front of it) Ubuntu looks in all the folders listed in your $PATH variable. Your can see it by running:
echo $PATH
If Ubuntu doesn't see the command in any of those folders, it will say that it can't be found.
You can solve this problem by altering your $PATH variable in your profile. Go to your home directory and open the ".profile" file (note the period in front) and add the following to the end:
PATH = "/path/to/folder/with/file/:$PATH"
However, if it's a program you could see yourself using a lot in the future and your don't want to clutter up your $PATH, I'd recommend sticking the finished command in your "/usr/local/bin" folder instead. I find that folder gets used as an "odd sock drawer" of programs you create/compile yourself, so I usually end up putting my personal tools in there rather than modifying my $PATH.

That's how it's supposed to work, not only for Python scripts but for any executable. See: Why do you need ./ (dot-slash) before executable or script name to run it in bash?

Please Try this one
On unix systems, Python scripts can be made executable using the following process:
Add this line as the first line in the script:
#!/usr/bin/env python
At the unix command prompt, type the following to make myexe.py executable:
$ chmod +x myexe.py
Move myexe.py into your bin directory, and it will be runnable from anywhere.
$ cp myexe.py /usr/bin
OR
$ cp myexe.py /usr/local/bin
So myexe.py
#!/usr/bin/env python
print("Hello This is executable python script")
Now Go to terminal and type myexe.py
$ myexe.py
Hello This is excutable python script
If you want to run by double-clicking remove .py extention
source link

I have found a way to solve this. I still include the shebang #!/usr/bin/env python3.6 at the top of Python script. Then I would go to cd /etc->sudo nano bash.bashrc, and at the very last line, all I did was add a line (alias nameofscript = "./nameofscript"). From there I restarted my Ubuntu, and was able to run my Python script just by the name of the script. Thank you everyone for the help.

Related

A python problem in running the command to execute a python file in vs code

I was trying to run a python file "exe.py" on vs code by typing:
python3 .\exe.py
But it comes with the following replys from vs code:
python3: can't open file '/Users/exercise/my-python-app/myenv/.exe.py': [Errno 2] No such file or directory
No ideas why couldn't it works given that I already installed the python package and running the command in appropriate environment.
You are running
python3 .\exe.py
which is escaping the e and therefore is replaced by e as there's no matching escape char and it becomes
python3 .exe.py
You need, as other response states
python3 exe.py
or
python3 ./exe.py
In fact python3 is installed in your system but you are typing incorrectly the command. Imagine that you have the python file named exe.py with the following code
print("Hello world")
If you are in the same directory of the file you can execute it using the command
python3 exe.py
Another way to execute exe.py is using the shebang line. The shebang is a line that you can write to tell to the operative system which executable must use to interpret the code of the file. If you add the typical shebang for python3 in linux at the beginning of exe.py
#!/usr/bin/env python3
print("Hello world")
and you tip the command
./exe.py
you will see the result of the execution too. If you get an error probably you have to give permissions to the file with the command
chmod 777 exe.py
You can find a lot of resources talking about the shebang. The following link talks about the shebang in python
https://www.pythonpool.com/python-shebang/
I hope you found it useful.
Greetings.

Executing a python script from the terminal in Unix

I have a python script and I can't figure how to execute it in the terminal. The script has the #!/usr/bin/python at the beginning, is executable and I've tried locating myself in the right directory and python name.py but what I want to print (ergo what the script says it should print) doesn't print in the terminal.
I feel I'm missing something... I just started with this so... Help!
If name.py is executable, you can run it using:
./name.py
As for the #!, it is better to use as a first line:
#!/usr/bin/env python
This way path to python interpreter is not hardcoded, the first python found in $PATH is used instead.
Also: it makes your script to run in fresh environment (you can see man env for more information).

Execute script in Python2 on Unix Command Line

Yes, I know I can do
python2 cal.py
What I am asking for is a way to execute it on the command line such as:
calpy
and then the command afterwards. I put in in a path and when I write cal.py in the command line:
/usr/bin/cal.py: line 5: print: command not found
I don't want to issue cal.py to run my script, I want it to be issued with calpy
I'm running Arch Linux if that helps, thanks. Sorry for my English.
In order for bash to know to run your script via the Python interpreter, you need to put an appropriate shebang at the start. For example:
#!/usr/bin/python
tells bash to run /usr/bin/python with your script as the first argument. I personally prefer
#!/usr/bin/env python
which is compatible with virtualenv. You also need to ensure that the permissions on your script allow it to be executed:
~$ chmod +x path/to/cal.py
Finally, in order to call cal rather than path/to/cal.py, you need to remove the .py extension and make sure that the directory containing cal is in your command search path. I prefer to add ~/bin to the search path by modifying the $PATH environment variable in ~/.bashrc:
export PATH=$HOME/bin:$PATH
then put my own executables in ~/bin. You could also copy (or symlink) cal to one of the system-wide binary directories (/bin or /usr/bin), but I consider it bad practice to mess with system-wide directories unnecessarily.
Ok, you need a couple of things for achive what you want.
First you have to tell your script "How" is going to execute/interpret it. You can do this writting
#/usr/bin/env python
at the very beggining of the file.
The problem you have is the system is trying to execute the script using bash. And in bash there is no print command.
Second you need give execution privileges to your script. And of course if you want to call your script through the command "calcpy", the script has to be called like that.
Put this (exactly this) as the first line of your script:
#!/usr/bin/env python

Executing python program

I have been searching the web for an answer now for quite a while, but this is giving me really headache:
I am using Ubuntu 12.04 and I want to execute a Python script from the terminal without using the full path.
So i added /home/kyril/python/scripts/ to the PATH variable through putting the following into ./bashrc:
kyrilpathvariable="/usr/lib/lightdm/lightdm:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/kyril/Python/scripts/:/home/kyril/Bash/scripts"
if [ "$kyrilpathvariable" = "$PATH" ]; then
echo PATH already exported
else
PATH=$PATH:/home/kyril/Python/scripts/
PATH=$PATH:/home/kyril/Bash/scripts/
export PATH
fi
(I know the if clause is not necessary but I did not like to have everything two times in my PATH if I type exec bash.)
Now the problem: this perfectly works for my Bash scripts, so after making them executable via chmod I can just type $ script.sh and it is executed. However if I type $ python3 script.py the following error is raised: python3: can't open file 'script.py': [Errno 2] No such file or directory
if I type in the full path to the script it works. Anybody has an idea what I am doing wrong? Do I have to add the directory to the PYTHONPATH? (As I understood this only helps for importing modules).
Thanks guys!
When invoking python3 directly, python runs the script file you told it to, without using $PATH to find it. PYTHONPATH is irrelevant--that's used for searching for Python modules.
I'm guessing you're having issues with the wrong interpreter getting invoked when you run script.py by itself. I don't know what the first line of your script is, but it should be this:
#!/usr/bin/env python3
Or if you need even finer control:
#!/usr/bin/env python3.2
And for Python 2 scripts:
#!/usr/bin/env python2
Or:
#!/usr/bin/env python2.7
You should check that these executables exist on your system before trying to use them.
I would guess that path variables are ignored when python searches for the input-file. Python starts searching for 'script.py' in the current directory, not knowing that there is a path variable declared for that file, and therefore cannot find it.
Unfortunately I'm not sure how to solve it but maybe someone more experienced with variables can enlighten us?
python3 $(type -P script.py)
Tells Bash to look in the PATH for the executable file and supply its location and name.
For example:
$ type -P script.py
/usr/local/bin/script.py
To avoid duplicate entries in the path, you can do:
for dir in Python Bash; do
dir_to_add="$HOME/$dir/scripts"
case ":$PATH:" in
*:"$dir_to_add":*) ;; # path already contains dir, do nothing
*) PATH+=":$dir_to_add" ;;
esac
done

starting Python IDLE from command line to edit scripts

I've tried many variations of this command: idle.py -e filepath, but it simply starts IDLE like normal, not opening any extra windows for editing, and not throwing any errors.
So how can I do the equivalent of opening IDLE, file>open>filepath via the command line (or perhaps even a Python module)?
You need to do as stated in the main.py file of the idelib folder (C:\Python33\Lib\idlelib), at least on the python 3.3 version explains that:
IDLE main entry point
Run IDLE as python -m idlelib
So with python -m idlelib <script_to_edit> you will be able to open and edit the script with idle. I haven't checked with previous versions but it could be the same comand
This is also documented on the changelog of the version 3.3.3
Make a new text file, and put something like this in it:
C:\Python26\Lib\idlelib\idle.pyw "C:\file1.py" "C:\file2.py"
In your actual script, you'll replace "C:\file1.py" and "C:\file2.py" with your files' paths, save as a .bat, and then launch it. That should do what you want.
Please forgive me for bumping such an old thread, but I've been teaching myself linux and python with the help of the community, and was trying to figure out how to invoke IDLE2 and IDLE3 from the command line. I came across this post some of the solutions seemed a bit complicated for my application. Then it occurred to me that I could just put syslinks in the /usr/bin/ path for each.
sudo ln -s idle-python3.1 idle3
sudo ln -s idle-python2.6 idle2
to address the OP. From the directory the script is located, type:
idle3 abc123.py
or
idle2 abc123.py
I'm just so damned happy that I finally had a "light bulb" go off that I wasn't going to let a 2 year old post stop me from posting my solution.
Rarely the native os is useful. I created a 'win batch file, in the folder with my .py files:
start /MIN cmd /C c:\Python27\lib\idlelib\idle.py -e %1 %2 %3 %4 %5 %6
This can open up to six files from cmd line in one shot. Just type the name of the batch file, followed by from zero to six filenames. Also if one or more files you specify are not found, idle opens these as new document(s).
first make sure you have location of idle in path
I am using "python3.5".So mine looks like this:
C:\Program Files\Python35\Lib\idlelib.Yours may differ.
use this following command:idle -r file_name.py to run the file
or just idle file_name.py to edit
or start idle -r file_name.py ^&exit
you can just program in Python to edit your Python files. A simple example. say you want to search for a word and then replace it with something else.
import fileinput
import os
os.chdir( os.path.join("c:\\","path") )
for file in os.listdir("."):
for line in fileinput.input(file,inplace=0):
if "search word" in line :
line=line.replace("search word","new word")
print line
(use inplace=1 to do in place editing.). Then save and run the script as normal Python script using the interpreter.
Just add IDLE's path to your PATH environment variable.
For example I created an environment variable called IDLE_PATH and set the value to C:\Python27\Lib\idlelib
Then in my PATH variable I added ;%IDLE_PATH%; and open a new cmd prompt or in console2 just open a new tab and run idle <file_name> to open the file, you will be able to do this from any directory. In IPython console add an ! before the command, for example !idle test.py.
Congrates, Now you're a python pimp!
paste the idlelib to your system path or user path, environment variable.for example, like this
C:\Program Files\Python310\Lib\idlelib
then type idle in your command prompt. done.

Categories