0

Distro: Debian 11
Python: 3.9.2
Shell: Bash
I'm attempting to permanently update a user's path using Python. I want to essentially do the equivalent of this using Python:

export PATH="$PATH:/usr/local/bin/folderA"  
export PATH="$PATH:$HOME/.local/share/folderB/bin"  
echo export PATH="$PATH:$HOME/.local/bin" >> "$HOME"/.bashrc  

In Python I attempted:

import os  
from pathlib import Path  

dir_home = str(Path.home())  

os.system('export PATH=$PATH:/usr/local/bin/folderA')
os.system('export PATH=$PATH:' + dir_home + '/.local/share/folderB/bin')
os.system('echo export PATH=$PATH:' + dir_home + '/.local/bin >>' + dir_home + '/.bashrc')

The echo export PATH="$PATH:$HOME/.local/bin" >> "$HOME"/.bashrc works but the other two lines don't get input into the $PATH.

I don't care how it gets done though. I am using this method as I thought it was the way to do it.

Thanks

2
  • 1
    You cannot modify one process' environment from a subprocess. Commented Apr 20, 2022 at 15:32
  • That info really helped. Wasn't thinking. I will attempt to run all the commands in one os.system call and see if that works. Like this: stackoverflow.com/questions/20042205/… Thanks! Commented Apr 20, 2022 at 15:55

1 Answer 1

0

Run all the commands at once with one os.system call.

#################################################################################
import os
from pathlib import Path

dir_home = str(Path.home())

p1 = 'export PATH=$PATH:/usr/local/bin/folderA; '
p2 = 'export PATH=$PATH:' + dir_home + '/.local/share/folderB/bin; '
p3 = 'echo export PATH=$PATH:' + dir_home + '/.local/bin >>' + dir_home + '/.bashrc'

os.system(p1 + p2 + p3)
#################################################################################
Sign up to request clarification or add additional context in comments.

2 Comments

How can this possibly work? As noted in comments a subprocess can't change the environment of the parent, and os.system will make a subprocess. The final line will work to make a change to your .bashrc though.
I don't know anything, but it worked on my system.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.