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?

2
  • It seems that it's not possible to change the working directory from a child process. Check this thread: stackoverflow.com/questions/3786678/… Commented Dec 29, 2021 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. Commented Dec 29, 2021 at 16:29

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.