问题
Well, as we all known, creating an alias in a terminal shell is quite easy:
ZZ:~ zhangzhao$ alias c='uname'
ZZ:~ zhangzhao$ c
Darwin
ZZ:~ zhangzhao$
But now I want to do the same thing through a Python3 script. I've checked the ref manual and found these sort of command work can be solved using subprocess
module.
Then I write the script below:
import subprocess
subprocess.call(["alias", "c=\'uname\'"])
But note that this operation will not take effect to the shell you are currently using, instead, it will use a subshell and then leave. So what this script has done is totally in vain.
So my problem is: how to create an alias in the currently using shell by executing a python script?
回答1:
In general, you can't
All alias you set in only works in current shell and new aliaes can be added only by shell it self rather than sub-shell or sub-process.
In hack way, you can use gdb to attach you parent shell and change its alias table. But in modern Unix, child process is not allowed to attach parent process. You need to low down the system security level
来源:https://stackoverflow.com/questions/19946321/create-unix-alias-using-a-python3-script