1

I'm looking to keep a change in my python working directory; however, when I change the directory with the following code:

import os
os.chdir('Path')

and exit out of python, the working directory reverts back to the default while attempting to run a script within this working directory.

How do I keep the changed working directory? I'm using a Mac (if that makes a difference). Any help is greatly appreciated for this novice looking to self teach python.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
zrfran2
  • 19
  • 1
  • 4
    This isn’t really possible: each process has its own working directory, and can’t change its parent’s (except via invasive, inadvisable means). – Davis Herring Dec 24 '18 at 19:00
  • a bad workaround could be to run shell command `cd` within python – Osman Mamun Dec 24 '18 at 19:03
  • There may be another workaround, depending on what you're ultimately trying to do. Do you have a separate Python script, and just want to execute from within Terminal from a directory other than the one it's in? – Bill M. Dec 24 '18 at 19:07
  • 3
    @mamun: That would launch a new shell and change the new shell's working directory, not the parent shell's working directory. – user2357112 Dec 24 '18 at 19:18
  • 2
    What are you really trying to do after changing the working directory ? Are you looking forward to execute a script in the then changed directory ? Are you trying to import a module from there ? Are you trying to open a file ? – Chgad Dec 24 '18 at 20:27
  • In a similar situation, I ended up having my script just output the desired folder path to stdout, and made a wrapper alias like `cd $(python ~\my-script.py)` – Blorgbeard Dec 24 '18 at 22:06

0 Answers0