首页 > 解决方案 > 如何引用脚本以使单引号不消失?

问题描述

我想使用 python 脚本在文件中添加一些单词。这是我的脚本(名称为test.py)以及我如何执行脚本。

import os
some_python_words = "sys.path.insert(0, os.path.abspath('..'))\n"
scripts = "echo '%s' >> 'conf.py' " % (some_python_words)
os.system(scripts)

正如我在终端中执行的那样python test.py。我的文件中写的是

sys.path.insert(0, os.path.abspath(..))

的单引号没''..。我应该怎么办?

标签: python

解决方案


这是因为在 shell 中处理了单引号和双引号。单引号字符串不能有内部单引号,但双引号可以。请参阅Bash 中单引号和双引号之间的区别以获得出色的文章。

只需在创建 shell 字符串时更改您的引用

scripts = """echo "%s" >> 'conf.py' """ % (some_python_words)

推荐阅读