Skip to content
Advertisement

Infinite while not working with os.execvp

I am programming in python which involves me implementing a shell in Python in Linux. I am trying to run standard unix commands by using os.execvp(). I need to keep asking the user for commands so I have used an infinite while loop. However, the infinite while loop doesn’t work. I have tried searching online but they’re isn’t much available for Python. Any help would be appreciated. Thanks

This is the code I have written so far:

import os
import shlex

def word_list(line):
    """Break the line into shell words."""
    lexer = shlex.shlex(line, posix=True)
    lexer.whitespace_split = False
    lexer.wordchars += '#$+-,./?@^='
    args = list(lexer)
    return args



def main():
    while(True):
        line = input('psh>')
        split_line = word_list(line)

        if len(split_line) == 1:
            print(os.execvp(split_line[0],[" "]))
        else:
           print(os.execvp(split_line[0],split_line))

if __name__ == "__main__":
    main()

So when I run this and put in the input “ls” I get the output “HelloWorld.py” (which is correct) and “Process finished with exit code 0”. However I don’t get the output “psh>” which is waiting for the next command. No exceptions are thrown when I run this code.

Advertisement

Answer

Your code does not work because it uses os.execvp. os.execvp replaces the current process image completely with the executing program, your running process becomes the ls.

To execute a subprocess use the aptly named subprocess module.


In case of an ill-advised programming exercise then you need to:

# warning, never do this at home!
pid = os.fork()
if not pid:
    os.execvp(cmdline) # in child
else:
    os.wait(pid) # in parent

os.fork returns twice, giving the pid of child in parent process, zero in child process.

Advertisement