user1562862
user1562862

Reputation: 337

Create an alias in bash when exiting a python script

I have written a shell in python (using the cmd module) and when using this shell, certain information about commands run ect. is outputted to a text file. I would like to write a piece of code that creates an alias to view the text file in my bash shell (eg as if I had executed the following command: alias latest.trc='less <path to file> My best current effort is:

x="alias %s = 'less %s'" % (<alias name>, <path>)
y=shlex.split(x)
atexit.register(subprocess.call, y)

This works to execute some commands on exit, eg if x="echo 'bye'" but I get the error

OSError: [Errno 2] No such file or directory

The path I am entering is certainly valid and if I run x directly from the command line it works.

Any help either with why my code is hitting an error or a better way to achieve the same effect would be greatly appreciated.

Upvotes: 0

Views: 224

Answers (1)

lbolla
lbolla

Reputation: 5411

You get an error because alias is a bash command, not an executable. You must run subprocess.call inside a shell:

import subprocess                                                              
import atexit                                                                  
import shlex                                                                   

x="alias %s = 'less %s'" % ('a', 'whatever')                                   
y=shlex.split(x)                                                               
atexit.register(lambda args: subprocess.call(args, shell=True), y)             

But, given the fact that subprocess spawns a new process, whatever changes are made to the environment it runs into, are lost on exit.

You'd better instead create a file where you put all these aliases and source it by hand when you need to use them.

Upvotes: 1

Related Questions