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

Arkham Angel
  • 309
  • 1
  • 5
  • 18
  • 1
    You cannot modify one process' environment from a subprocess. – Sören Apr 20 '22 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: https://stackoverflow.com/questions/20042205/calling-multiple-commands-using-os-system-in-python Thanks! – Arkham Angel Apr 20 '22 at 15:55

1 Answers1

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)
#################################################################################
Arkham Angel
  • 309
  • 1
  • 5
  • 18
  • 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. – Mark Ransom Apr 20 '22 at 16:38
  • I don't know anything, but it worked on my system. – Arkham Angel Apr 20 '22 at 16:41