我正在使用 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)
我能做到這一點的最好方法是什么?
uj5u.com熱心網友回復:
您在該字串文字中已經有一個#字符 in $#,所以我不確定問題出在哪里。
正如您所注意到的, Python 將"""字串文字視為一個大字串、換行符、注釋式序列以及所有內容,直到結尾"""。
要通過 raw 也傳遞轉義字符(例如\n,\n而不是換行符),您可以使用r"""...""".
換句話說,與
with open("x", "w") as f:
f.write("""x
hi # hello world
""")
你最終得到一個包含
x
hi # hello world
uj5u.com熱心網友回復:
就您更廣泛的目標而言,從 Python 腳本撰寫帶有 bash 函式檔案的檔案似乎有點任性。
這不是一個真正可靠的做法,如果您的用例特別要求您通過腳本定義 bash 函式,請進一步解釋您的用例。一種更清潔的方法是:
定義一個 .sh 檔案并從那里讀取內容:
# function.sh
my_function() {{
# Some code
}}
然后在你的腳本中:
with open('function.sh', 'r') as function_fd:
# Opened in 'append' mode so that content is automatically appended
with open(os.path.join("location","filename"), "a") as target_file:
target_file.write(function_fd.read())
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/432413.html
