0

I want to create an alias' through python program. I intend to use python as a replacement for shell scripting.

What I tried is:

import os

os.system('alias go2dir="cd /i/want/to/goto/this/dir"')

...and it does not work. I know the reason - that system command 'alias...' is getting executed in another shell and not in the current one where this python script is executed. So, that alias is not available to this shell.

What I don't know is - (In general,) how do we execute a command from a python program in the same shell where this python program is being executed. So that (in this case) the alias is available till the shell terminal is open?

Learner
  • 533
  • 5
  • 18
  • 1
    It's not possible to execute a python command in the original shell, since Python is a separate process. – Barmar May 15 '20 at 20:25
  • 1
    The only way to execute something in the same shell is with the `source` command, and it has to be shell commands. – Barmar May 15 '20 at 20:26
  • Yes, so how do we solve this problem? If I just use a bash script and create the alias through it (i.e. run it in the terminal - `source createalias.sh`), the aliases created by the bash script will be available in that terminal. I want to achieve the same from python program. – Learner May 15 '20 at 20:29
  • Creating aliases is not something that can be delegated to another program. – user2357112 May 15 '20 at 20:30
  • @BrianMcCutchon - yeah, I understand it does not work the way I was thinking of. The solutions look like hacks to me. Short answer is it's not possible in Python. – Learner May 22 '20 at 08:04

1 Answers1

0

The way other applications that want to automate actions in the user's shell work is that they write shell commands to their standard output. Then you can execute them with eval.

makealias.py:

print('alias go2dir="cd /i/want/to/goto/this/dir"')

Then in bash:

eval "$(python makealias.py)"

An example of a standard Unix program that works like this is tset with the -s option.

Barmar
  • 741,623
  • 53
  • 500
  • 612