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???
-
1What do you mean by _maintain working directory that I changed before_? – AMC Jan 17 '20 at 01:55
-
I mean when I reopen python. When I reopen python I always write import os, os.chdir(Path). – chanyoung Jan 17 '20 at 01:59
-
Ah, I don't know if that's possible. Why do you need to do this? – AMC Jan 17 '20 at 02:01
-
I just want to change original working directory – chanyoung Jan 17 '20 at 02:02
-
1Which can be done using `os.chdir`, right? Case closed? – AMC Jan 17 '20 at 02:03
-
Yes, that I mean. – chanyoung Jan 17 '20 at 02:15
-
That's it, then, we're done here? – AMC Jan 17 '20 at 02:17
-
Yes. It is done – chanyoung Jan 17 '20 at 02:40
1 Answers
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!

- 30,189
- 5
- 49
- 65