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?

5
  • 1
    It's not possible to execute a python command in the original shell, since Python is a separate process. Commented May 15, 2020 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. Commented May 15, 2020 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. Commented May 15, 2020 at 20:29
  • Creating aliases is not something that can be delegated to another program. Commented May 15, 2020 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. Commented May 22, 2020 at 8:04

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.