简体   繁体   中英

How to make python program “.py” executable?

I need to make a py program run on command just by name I can do that in by put the executable in /usr/bin/executable_program

yes. I know I can make it by:

chmod +x file.py
./file.py

I just want when I write the program name "executable_program" in terminal it runs without the "./" and the ".py"

Thank you...

I just want when I write the program name "executable_program" in terminal it runs without the "./" and the ".py"

You need to do the following things:

  1. Add the shebang at the top of your file, #!/usr/bin/python

  2. Make the file executable chmod +x foo.py

  3. Move it to somewhere that is in your $PATH , for example /usr/local/bin

To get rid of the .py , simply rename the file: sudo cp foo.py /usr/local/bin/foo

burhan@sandbox:~/pytemp$ cat foo.py
#!/usr/bin/python
print('Hello World!')
burhan@sandbox:~/pytemp$ chmod +x foo.py
burhan@sandbox:~/pytemp$ sudo cp foo.py /usr/local/bin/foo
burhan@sandbox:~/pytemp$ foo
Hello World!

You can create a directory in your home, for example:

$ mkdir ~/bin

Then add that directory to PATH variable in your .bash_profile with your favorite editor:

PATH=$PATH:$HOME/bin
export PATH

and then save the changes.

Now, open a new terminal and put your file in ~/bin . After that, you can run your file without using ./ before it.

Try adding your program to your path.

If you just export PATH=$PATH:. at the command line it will only last for the length of the session though.

If you want to change it permanently add export PATH=$PATH:. to your ~/.bashrc file (just at the end is fine)

https://unix.stackexchange.com/questions/3809/how-can-i-make-a-program-executable-from-everywhere

I give you a example, write "test" file like this, not end with ".py". The first comment line is your python interpreter path:

#!/usr/bin/python2.6
print 'helloworld'

Then chmod 711 test;

Then export your test file path to $PATH(system path);

PATH=$PATH:$HOME/bin
export PATH

Finally you can run test like this :

test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM