1

I am trying to write a program that will change the current directory in zsh without creating a new instance of zsh. Might sound confusing but what I've tried so far should help with that.

Say zsh is currently in the "Users" directory as in:

$ /Users/ →

If I run the following on Python:

os.system("cd projects")
os.system("zsh")

It changes zsh to the "Projects" directory:

$ /Users/ → python main.py
$ /Users/Projects/ → 

But this creates a new instance of zsh and running exit doesn't close the Terminal window. Instead, I'll need to rerun exit.

Is there anyway to get Python to change current directory in zsh without starting up another instance of it?

Praanto
  • 216
  • 4
  • 14
  • It seems that it's not possible to change the working directory from a child process. Check this thread: https://stackoverflow.com/questions/3786678/change-working-directory-in-shell-with-a-python-script – Maciej Czarnecki Dec 29 '21 at 15:53
  • It's not changing anything in your *current* shell session; your Python script starts a new instance of `zsh`, true, but the Python script is also still running, blocking until the new `zsh` exits, at which point `os.system` returns and your Python script can continue. Also, I cannot reproduce the working directory having been changed by the code as show. The first `os.system` starts a new shell, executes the `cd` command, then that shell *exits*. The shell started by `zsh` will still have whatever working directory Python has. – chepner Dec 29 '21 at 16:29

1 Answers1

1

Seems you're looking for the os.chdir(path) method bundled with Python.

You must set a new route (absolute or relative) as the path parameter and it will change your working path to that route.

Matías Zanolli
  • 468
  • 3
  • 8