1

I used Context Manager: cd from here: How do I "cd" in Python?

import os

class cd:
    """Context manager for changing the current working directory"""
    def __init__(self, newPath):
        self.newPath = os.path.expanduser(newPath)

    def __enter__(self):
        self.savedPath = os.getcwd()
        os.chdir(self.newPath)

    def __exit__(self, etype, value, traceback):
        os.chdir(self.savedPath)

Example

import subprocess # just to call an arbitrary command e.g. 'ls'

# enter the directory like this:
with cd("~/Library"):
   # we are in ~/Library
   subprocess.call("ls")

# outside the context manager we are back wherever we started.

Why not work this code if I use like this:

str = "~/Library"

with cd(str):
   subprocess.call("ls")

Error:

OSError: [Errno 2] No such file or directory: 'cd ~/Library'
Community
  • 1
  • 1
tmsblgh
  • 517
  • 5
  • 21

1 Answers1

3

Your example code seems to work as it should. I can only duplicate your error if I added 'cd' to the value of str such that it tried to change to a directory called 'cd ~/Library'. That is also what seems to have happened based on the error message you show.

Broken

str = "cd ~/Library"
with cd(str):
   subprocess.call("ls")

Fine

str = "~/Library"
with cd(str):
   subprocess.call("ls")
Sam
  • 330
  • 1
  • 4
  • 11