gpt4 book ai didi

python - 如何在Python中将字符串作为变量传递?

转载 作者:行者123 更新时间:2023-11-30 22:57:30 26 4
gpt4 key购买 nike

我使用了上下文管理器:从这里开始: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'

最佳答案

您的示例代码似乎可以正常工作。如果我将“cd”添加到 str 的值中,以便它尝试更改到名为“cd ~/Library”的目录,我只能重复您的错误。根据您显示的错误消息,这似乎也是发生的情况。

破损

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

还好

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

关于python - 如何在Python中将字符串作为变量传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36609626/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com