0

End goal: After running a script regardless of ending perfectly or erroring out, I would like to have my ipython environment revert back to the directory it was in before running the script.

I have successfully used the advice given in the SO post,

how-do-i-change-directory-back-to-my-original-working-directory-with-python.

This works great if the script runs without failing.

Ideas:

1) I have considered wrapping my code in one large try: and except: utilizing the advice in the post mentioned above. As this would surely handle the issue. However, it seems tedious and unnecessary to have to write this into all my scripts.

2) I was thinking a good a solution would be to have ipython automatically run a "revert directory" script after every user ran script, that would change the directory back to the original one. I have looked around a bit to see how one would configure ipython to run a script automatically after every run. From my search so far I have not found this to be an option. I was expecting to find a method to accomplish this through the ipython config file.

3) Another solution that would be easy would be to somehow use the information found by using the line magic command %dhist. As the first result given by this command is the original directory that ipython was opened in. However, other than having the results print from executing the command %dhist... I am not sure how to work with the printed information.

4) I must be not searching the right terms, as I feel like this is probably something that is possible or has been asked. If indeed someone has asked this, please point me in the right direction and I will remove this question promptly.

Relevant information:

Working on os x

Using Jupyter QtConsole 4.3.1

IPython 6.2.1

Kyle Swanson
  • 1,308
  • 1
  • 12
  • 20
  • Why is all of your code calling `os.chdir()`? – Blender Feb 01 '18 at 16:51
  • Also, you may want to look at the second and third answer to your linked question. Using `try...finally` or a context manager will ensure the code will change back to your old directory is run even if an exception is raised. – Blender Feb 01 '18 at 16:54
  • @Blender Good question. Some of this code I wrote while still being inexperienced and it seemed ok at the time. I will rewrite the code but at the moment I don't have the time as I have pressing matters rapidly approaching. In regards to your second comment: I am not sure I see the difference between wrapping my code in `try and excepts` vs inserting `try and finally`. I agree that these are solutions. – Kyle Swanson Feb 01 '18 at 17:12

0 Answers0