Andrei Ciobanu Andrei Ciobanu - 1 year ago 83
Python Question

Python 'source HOME/.bashrc' with os.system()

I am writing a python script (Linux) that is adding some shell aliases (writes them to

HOME/.bash_aliases
).

In order to make an alias available immediately after it was written I should issue the following bash built-in:

source HOME/.bashrc


source
is a bash built-in so I cannot just:

os.system(source HOME/.bashrc)


If i try something like:

os.system('/bin/bash -c source HOME/.bashrc')


...will freeze the script (just like is waiting for something).

Any suggestions ?

Answer Source

What you want is not possible. A program (your script) cannot modify the environment of the caller (the shell you run it from).

Another approach which would allow you to do something close is to write it in terms of a bash function, which is run in the same process and can modify the caller. Note that sourcing during runtime can have possible negative side-effects depending on what the user has in their bashrc.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download