Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/unix/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中将字符串作为变量传递?_Python - Fatal编程技术网

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

如何在Python中将字符串作为变量传递?,python,Python,我在这里使用了Context Manager:cd: 范例 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 whereve

我在这里使用了Context Manager:cd:

范例

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
重命名为与内置名称不冲突的名称。请重新格式化代码,以指示
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
\uuuuuuuuuuuuuuuuuuuuuuuu。。我将str重命名为cd_path,但它仍然不起作用。你是对的,我将“cd”留在那里,我应该复制我自己的代码。。
str = "cd ~/Library"
with cd(str):
   subprocess.call("ls")
str = "~/Library"
with cd(str):
   subprocess.call("ls")