1

I want to change a user's current working directory when they run a Python script. For example, if I have the following script called chdir.py:

import os
os.chdir('Desktop')

I want to be able to do this:

$ pwd
/Users/me
$ python chdir.py
$ pwd
/Users/me/Desktop

I know that os.chdir(path) changes the working directory during the runtime, but it resets when the script exits. Is there any way to prevent this?

Ben Botvinick
  • 1,311
  • 1
  • 10
  • 30
  • 3
    I don't think it is possible in Python. But it is possible in a normal bash script. You just need to source it: `source chdir.sh`. – Sraw Aug 07 '18 at 03:20
  • As @Sraw suggested, you can refer this link for bash script [SO Question](https://stackoverflow.com/questions/3879431/how-to-run-cd-in-shell-script-and-stay-there-after-script-finishes) – Sociopath Aug 07 '18 at 03:22
  • As a side note, I would suggest you rethink your problem statement. Why do you wanna do it? You may better add the location to system variables such as `$PATH`, `$PYTHONPATH` etc. depending on your problem. You may wanna use `import sys; sys.path.append(your_directory)` – Ravi Joshi Aug 07 '18 at 03:30
  • @RaviJoshi my goal was to manipulate the path of a `cd` command as a spell checker. So if you enter `cd Dekstop` it looks in the current path and sees that the closest match is `Desktop` and changes directories to there instead. – Ben Botvinick Aug 07 '18 at 03:46
  • You need to hook your program with the terminal. Alternatively, you may design your own terminal, where you have full control over the user input. – Ravi Joshi Aug 07 '18 at 03:58

1 Answers1

0

I don't think it is possible because the current working directory is an attribute of a process. This means it cannot be changed by another program, such as your python script.

jh314
  • 24,533
  • 14
  • 58
  • 79