create unix alias using a python3 script

百般思念 提交于 2021-02-05 09:06:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!