1

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?

Zhao Zhang
  • 399
  • 1
  • 3
  • 14
  • 2
    Short answer: You can't. – Ignacio Vazquez-Abrams Nov 13 '13 at 05:54
  • If you are using this alias to make more calls in your python script, you can make a python variable equal to the string of the alias you want to make, and just make calls with that variable. Otherwise I don't think it is possible to make an alias with a python script so you can use it in a shell – samrap Nov 13 '13 at 05:55
  • The shell that calls Python is just itself another shell... – Nick T Nov 13 '13 at 05:58
  • Well, then I can just put the `alias c='uname'` into `.bash_aliases`. Then can I use any method to `source .bash_aliases` automatically after changing the `.bash_aliases`? – Zhao Zhang Nov 13 '13 at 05:58
  • I would put it into .bashrc – samrap Nov 13 '13 at 06:06
  • Then you may need to `source` it, right? To let it take effect immediately? – Zhao Zhang Nov 13 '13 at 06:11
  • besides, using `alias`es are not recommended even in `bash`. functions are preferred way. However, we still use aliases, when possible, because they are generally shorter to write. – anishsane Nov 13 '13 at 06:42

1 Answers1

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

cmchao
  • 86
  • 1
  • 3
  • @OP: How to attach gdb : you can check this answer as a sample code: http://stackoverflow.com/a/17398009/793796 – anishsane Nov 13 '13 at 06:50