【问题标题】:Is there any way to access variable like $var (similar to shell scripting) in python?有没有办法在 python 中访问变量,如 $var(类似于 shell 脚本)?
【发布时间】:2015-08-18 11:58:08
【问题描述】:

您好,我是 python 编程新手。

我想将文件从源复制到目标。我正在使用 shutil.copy2(src,dst)。 但是在 src 和 dst path 中,我想使用变量。

例如(变量​​名):pkg_name = XYZ_1000 所以 src 路径将是:/home/data/$pkg_name/file.zip

在shell中我们可以使用$pkg_name来访问变量,那么在python中有没有类似的方式?

主要问题是,如果我想在复制命令中使用变量,我该如何在 python 中实现呢? 提前致谢。

【问题讨论】:

标签: python shell variables copy language-comparisons


【解决方案1】:
pkg_name = XYZ_1000

使用格式()

src_path = "/home/data/{pkg_name}/file.zip".format(pkg_name=pkg_name)

src_path = "/home/data/%s/file.zip" % pkg_name

src_path = "/home/data/" + pkg_name + "/file.zip"

src_path = string.Template("/home/data/$pkg_name/file.zip").substitute(locals())
# Or maybe globals() instead of locals(), depending on where pkg_name is defined.

【讨论】:

  • 为了完整起见,我添加了一个string.Template 的示例。我实际上并不推荐使用它,如果你想将pkg_name 的值传递给read about it in the documentation,有几种方法。
  • @chepner,非常感谢
猜你喜欢
  • 1970-01-01
  • 2018-08-10
  • 1970-01-01
  • 2023-01-06
  • 2018-03-08
  • 2021-07-05
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
相关资源
最近更新 更多