简体   繁体   中英

C-style exec in python

In bash or C, exec will terminate the current process and replace it with something new. Can this functionality be accomplished in Python? I don't wish to simply execute some code then continue running the python script (even just to immediately exit), or spawn a child process.

My specific situation is the following. I'm developing a command line application (python + curses) to manage data generation/analysis in the context of scientific computing. It will sometimes be necessary for me to terminate the application and go wrangle with the data in a given subdirectory manually. It would be convenient if I could do something like:

# within python script; d=<some directory>
if exit_and_goto_dir:
    exec("pushd {}".format(d)) # C-style exec -- terminate program and execute new command

The following do not work, for example:

# attempt 1
if exit_and_goto_dir:
    os.system("pushd {}".format(d))
    exit(0) # pushd does not outlast the python script 

# attempt 2
if exit_and_goto_dir:
    os.chdir(d)
    exit(0) 

This behavior isn't really critical. There are plenty of work arounds (eg print the directory I care about to terminal then cd manually). Mostly I'm curious if it's possible. Thanks!

The os module contains Python wrappers for the various exec* functions in the C standard library:

>>> [method for method in dir(os) if method.startswith("exec")]
['execl', 'execle', 'execlp', 'execlpe', 'execv', 'execve', 'execvp', 'execvpe']

However, pushd is not an executable that you can exec but rather a bash builtin (and the same is true for cd ).

What you could do would be to change directory inside the python process and then exec an interactive shell:

import os
os.chdir(d)
os.execvp("bash", ["bash", "-login"])

Python's current directory will be inherited by the shell that you exec. When you later exit from that shell, control will then return to the original login shell from which you invoked python (unless you used that shell's exec command to launch python in the first place).

What you can't do is to modify the current directory of the calling shell from inside python, in order to return to the shell prompt but in a different working directory from when python was invoked. (At least there's no straightforward way. There is a hack involving attaching gdb to it, described here , but which only worked as root when I tried it on Ubuntu.)

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