comicosmos
comicosmos

Reputation: 111

execlp() in python

I was reading programming python 4th edition by Mark Luze, Oreilly, by teaching myself. There's an example on how to fork a child process, which I do not quite understand:

os.execlp('python', 'python', 'child.py', #other args#)

In an interactive shell(like bash), I know I can type python child.py #args# to ask python interpreter to run child.py with args. Why are there TWO 'python' in the execlp() function? If I put only one python in the function, I would get an error complainting cannot find file or directory, which is the 1st args of child.py

Upvotes: 8

Views: 11882

Answers (2)

phihag
phihag

Reputation: 287885

First of all, execlp is rarely used today. In most cases, you'd use the subprocess module, like this:

subprocess.call(['python', 'child.py'])

The first argument of execlp is the file you want to execute.

The latter arguments form the argument array to that program (sys.argv in Python). The first argument is then the name the program got invoked with. For example, Python sets the name to '-c' if the program is being run with the -c option. Similarly, grep behaves differently depending on the first argument, so that users can execute rgrep to imply grep -r.

Upvotes: 5

Martijn Pieters
Martijn Pieters

Reputation: 1122342

The first argument is the program to execute (found on the PATH). The rest are the sys.argv arguments to the program.

The first such argument is the program name used to invoke it, and the display value used in the OS process list. It is the value of sys.argv[0] in a python script.

Upvotes: 12

Related Questions