简体   繁体   中英

Executing Python code on UNIX

I have written a Python program to analyse a set of files present in a given directory, ie it asks for a path then it goes into the path directory and find specified files, process them and produces an output file. However, every time I want to execute the program on a UNIX machine I have to write python my_prog.py . Also, to process a directory the program must be copied to the directory first, then executed.

I want to make it so that in UNIX I type my_prog inside any directory the program be executed, which means getting rid of copying the program file to target directory. How can I do this?

Make your program executable with

chmod +x my_prog.py

put

#!/usr/bin/env python

(or a variation of this) at the top of your source file and place your my_prog.py script into a directory in your path (ie, somewhere in the set of directories as usually defined by the PATH environment variable which is searched for commands to be executed).

Once your program is in your path, you will be able to execute it from anywhere, ie, without having to place the program in your current directory or fully specifying the directory path to it.

You should be able to see the value of your current PATH environment variable in most shells with this command:

env | grep -i path

or

echo $PATH

Just in case, here is a bit more basic information on the PATH variable: http://www.cs.purdue.edu/homes/cs348/unix_path.html and http://kb.iu.edu/data/acar.html . Google will yield many more. Hope this helps.

与往常一样,添加一个shebang行,使其可执行 ,然后将其复制到$PATH的目录中。

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