2016-04-13 6 views
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' 
+2

は、なぜあなたはそれが動作しないと言うのですか?それは正常に動作するはずです。 – user2357112

+0

'str'の名前を、組み込みの名前と衝突しない名前に変更してみてください。 –

+1

'__enter__'と' __exit__'がクラス内のメソッドであり、関数ではないことを示すようにコードを再フォーマットしてください。 –

答えて

3

あなたのサンプルコードは正常に動作するようです。私はstrという値に 'cd'を追加して、 'cd〜/ Library'というディレクトリに変更しようとするとエラーを複製することしかできません。これはまた、あなたが表示するエラーメッセージに基づいて起こったようです。壊れた

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

ファイン

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

あなたは正しいです、私は 'cd'をそこに残して、私自身のコードをコピーする必要があります.. – tmsblgh

関連する問題