1
私はコンテキストマネージャを使用:Pythonで文字列を変数として渡すには?
str = "~/Library"
with cd(str):
subprocess.call("ls")
がエラー:
ここからCD:私はこのように使用している場合 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.
なぜ、このコードは動作しません
OSError: [Errno 2] No such file or directory: 'cd ~/Library'
は、なぜあなたはそれが動作しないと言うのですか?それは正常に動作するはずです。 – user2357112
'str'の名前を、組み込みの名前と衝突しない名前に変更してみてください。 –
'__enter__'と' __exit__'がクラス内のメソッドであり、関数ではないことを示すようにコードを再フォーマットしてください。 –