Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make a python file run without py extension

I had a small python script that takes input from the command line arguments and done some operations using the inputs taken and display the result

Below is the working example code

some_file.py

import sys

arguments = sys.argv
first_name  = sys.argv[1]
second_name = sys.argv[2]

print "Hello {0} {1} !!!!".format(first_name,second_name)

Now i am executing this as

python some_file.py Steve jobs

Result :

Hello Steve Jobs !!!!

Now what all i want is, i don't want to use python command before file name and extension of python file name, that is i want to run the file as a command tool as below

some_file  Steve Jobs

so what to do in order to run the python file as above ?

like image 206
Shiva Krishna Bavandla Avatar asked Jul 11 '13 11:07

Shiva Krishna Bavandla


People also ask

Do python scripts need a py extension?

It is the standard for all python scripts to have the . py or . pyc extension on them.

Can you run Python exe without Python installed?

Is it necessary to install Python to run a software written in Python? If the Python software is compiled to an executable (like an exe or app) then no, you do not need Python installed to run it as the compiler compiles the python interpreter into the executable.

How do I run a .py file directly?

To run Python scripts with the python command, you need to open a command-line and type in the word python , or python3 if you have both versions, followed by the path to your script, just like this: $ python3 hello.py Hello World! If everything works okay, after you press Enter , you'll see the phrase Hello World!

How do I run a non executable file in Python?

For example, if you have a file a.sh which is not executable to the shell, you can execute it by calling bash a.sh (which tells bash explicitly to execute it). If you have a non-executable file a.py , you can execute it by calling python a.py .


1 Answers

Unix-like OS solution: the first line of the file should be #!/usr/bin/python (or wherever the python interpreter is) and chmod u+x the script. Run it with ./some_file parameters.

If you want to launch it with some_file parameters simply make a link to the script in a directory which is already included into your PATH: sudo ln -s some_file /usr/bin.

So, here's the full procedure:

blackbear@blackbear-laptop:~$ cat > hw
#!/usr/bin/python

print "Hello World!"

blackbear@blackbear-laptop:~$ chmod u+x hw
blackbear@blackbear-laptop:~$ sudo ln -s hw /usr/bin
blackbear@blackbear-laptop:~$ hw
Hello World!
blackbear@blackbear-laptop:~$ 
like image 193
BlackBear Avatar answered Oct 19 '22 22:10

BlackBear