3

Does anyone know how someone would use Python to change the current directory a user is in?

I am currently working on a Python script. This script will be used by a user in a terminal/terminal emulator. When certain criteria is met, the script would move the user to the correct directory. The issue I am running into is that I can move the working directory for the Python script, but once the script exits the user is still in the directory they ran the script from. Any ideas on how to achieve this?

1
  • "once the script exits the user is still in the directory they ran the script from." - "users" aren't "in" directories; terminal processes are. Commented Mar 15, 2023 at 7:07

3 Answers 3

2

You could use absolute paths to files, or

os.chdir(path)

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

3 Comments

This just changes the working directory for Python. I want to change the directory the user is in. When the Python script exits, the user should be in a different directory from were they ran the script.
Then you want a shell script, not a Python script
Yeah, I guess I will have to make it a shell script. Thank you!
1

Sorry, you can't do that with a program that's launched in the normal way. At least, you can't in a POSIX-compliant OS.

When you run a script or program in the normal way it gets run in a new process, and of course any changes made in that new process don't affect the parent process: child processes inherit environment from their parent, the parent's environment can't by affected by any changes the child makes to its environment.

There's kind of a way around this: you can put a cd command into a script and then source that script, which executes the script in the current process rather than running it in a new process. I guess your Python code could create a tiny shell script that changes to the desired directory, but you will still need the user to source that script to make the actual directory change. When I need to do this for my own use, I just print the desired cd command to the shell so I can easily copy & paste it and then hit Enter. :)

Take a look here for more details about why cd is like this.

Comments

0

This may not be the perfect solution but it can be useful. With this commands you will have a new cmd promt open with the path in it. pd: only for windows users

import subprocess
import os
os.chdir('the\path\to\your\dir')
subprocess.run("start cmd", shell=True)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.