将主题标签写入文件
我正在使用 python 脚本创建一个 shell 脚本,我希望用注释对其进行注释。如果我想将带有主题标签的字符串添加到这样的代码部分:
with open(os.path.join("location","filename"),"w") as f:
file = f.read()
file += """my_function() {{
if [ $# -eq 0 ]
then
echo "Please supply an argument"
return
fi
echo "argument is $1"
}}
"""
with open(os.path.join("location","filename"),"w") as f:
f.write(file)
完成此操作的最佳方法是什么?
I am using a python script to create a shell script that I would ideally like to annotate with comments. If I want to add strings with hashtags in them to a code section like this:
with open(os.path.join("location","filename"),"w") as f:
file = f.read()
file += """my_function() {{
if [ $# -eq 0 ]
then
echo "Please supply an argument"
return
fi
echo "argument is $1"
}}
"""
with open(os.path.join("location","filename"),"w") as f:
f.write(file)
what is the best way I can accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您在该字符串文字中已经有一个
#
字符,在$#
中,所以我不确定问题是什么。正如您所注意到的,Python 将
"""
字符串文字视为一个大字符串、换行符、注释式序列等等,直到结尾"""
。要通过原始数据传递转义字符(例如
\n
作为\n
,而不是换行符),您可以使用r"""..."" “
。换句话说,
您最终会得到一个包含以下内容的文件
You already have a
#
character in that string literal, in$#
, so I'm not sure what the problem is.Python considers a
"""
string literal as one big string, newlines, comment-esque sequences and all, as you've noticed, until the ending"""
.To also pass escape characters (e.g.
\n
as\n
, not a newline) through raw, you'd user"""..."""
.In other words, with
you end up with a file containing
就您更广泛的目标而言,从 Python 脚本编写带有 bash 函数文件的文件似乎有点任性。
这并不是一个真正可靠的做法,如果您的用例特别要求您通过脚本定义 bash 函数,请进一步解释您的用例。一种更简洁的方法是:
定义一个 .sh 文件并从其中读取内容:
然后在脚本中:
In terms of your wider goal, to write a file with a bash function file from a Python script seems a little wayward.
This is not really a reliable practise, if your use case specifically requires you to define a bash function via script, please explain your use case further. A cleaner way to do this would be:
Define an .sh file and read contents in from there:
Then in your script: