0

I know how to change working directory by os.chdir(Path). But I want to maintain working directory that I changed before. Is it possible???

chanyoung
  • 13
  • 1

1 Answers1

0

Nope. That's an operating system thing: the Python subprocess is changing its working directory, but that can't affect its parent process (such as a Bash shell you're launching it from).

If the Python process is meant to change your directory - let's say you're writing your own improved cd program - you could do something like:

  • Have your program print the name of the directory to change to
  • Have your shell itself change to your program's output

For example, say you have a Python program like:

#!/usr/bin/env python

print('/tmp/pancakes')

You could run it from your shell this way:

$ pwd
/tmp
$ cd $(python mycd.py)
$ pwd
/tmp/pancakes

See? Now you've changed to the new directory! Alternatively, you could make a handy alias like:

$ pwd
/tmp
$ alias mycd='cd $(python mycd.py)'
$ mycd
$ pwd
/tmp/pancakes

so that you don't have to remember the syntax every single time. But really, without some dire platform-specific shenanigans (example: Changing a process's current working directory programmatically) but if you value your sanity, trust me, you really don't want to go down that road. You'd be much better off learning how to work within your OS's process model, even if it feels wonky, than to try to work around it.


Edit: you've added some clarifying answers since the post, which really changes what you were asking. That may be a little easier, but I still strongly suggest you not go down this path.

  • Consider that Python has a startup file.
  • Ponder that Python has exit handlers.
  • Wonder what would happen if an exit handler wrote your current working directory name out to a file.
  • Think of what would happen if the startup file read that file and changed to the directory named in it.
  • Realize that this is probably a Really Bad Idea because half the time you launch Python it'll be working in a different directory than you think it is. What happens if you run import foo? Who knows! Let's roll some dice and find out!
Kirk Strauser
  • 30,189
  • 5
  • 49
  • 65