我使用了Context Manager:cd from this: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)
实施例
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.
如果我这样使用,为什么不使用此代码:
str = "~/Library"
with cd(str):
subprocess.call("ls")
错误:
OSError: [Errno 2] No such file or directory: 'cd ~/Library'
答案 0 :(得分:3)
您的示例代码似乎可以正常工作。如果我添加' cd'我只能复制您的错误到str
的值,以便它尝试更改为名为' cd~ / Library'的目录。这也是基于您显示的错误消息而发生的事情。
断
str = "cd ~/Library"
with cd(str):
subprocess.call("ls")
精细
str = "~/Library"
with cd(str):
subprocess.call("ls")