1

I want to change dirs back in forth in python script. From Bash I would do cd "bla/bla" and then cd - or pushd "bla/bla" > /dev/null and then popd.

Python has no wrappers for pushd, popd, or - (which is a Shell variable). Is there a better way than:

import os
curr_dir = os.getcwd()
os.chdir('bla/bla')
...
is.chdir(old_dir)

OR

import path # after pip install https://github.com/jaraco/path.py
with path.Path('bla/bla'):
    ...

which includes another not-built-in dependency and is not very obvious, IMO

?

CIsForCookies
  • 12,097
  • 11
  • 59
  • 124
  • 1
    `pushd` and `popd` are shell functionality. It wouldn't make sense for Python to have wrappers for them; at most, such a wrapper could have a new shell change its working directory and exit, leaving the Python process's working directory unaffected. – user2357112 Oct 27 '19 at 12:07
  • Correct. I don't mean an actual wrapper (though it is what I wrote). What I meant is a `os.chdir()` with memory – CIsForCookies Oct 27 '19 at 12:10
  • You would have to define your own stack, as Python doesn't have one pre-allocated (like the shell does for use by `pushd` and `popd`. – chepner Oct 27 '19 at 13:40

1 Answers1

2

I don't think there's anything in os that does this:

from os import chdir, getcwd

_stack = []

def pushd(dir):
    global _stack
    _stack.append(getcwd())
    chdir(dir)

def popd():
    chdir(_stack.pop())

Given context I would prefer your with Path(dir): example in many situations though. You are presumably trying to get away from bash not replicate it :)

drekbour
  • 2,895
  • 18
  • 28