我目前正在使用Python脚本和Jenkins API为Jenkins构建创建日志文件。
以下功能创建构建的控制台输出的文本文件并将其保存到网络位置。我正在寻找文件网络路径,以便可以将其包含在自定义的电子邮件通知中。
只是想知道您是否可以帮助我获得预期的结果。谢谢。
代码:
job_list = ['project_name1', 'project_name2', 'project_name3']
def create_log_file(job_list):
log_file_info = []
for job in job_list:
file_name = os.path.join('//network_location/folder/subfolder1/subfolder2/subfolder3/Jenkins_Build/buildlog/windows/', job + "_" + current_date + file_format)
file_content = get_console_output(job)
with open(file_name, 'w', encoding="utf-8") as f:
f.write(file_content)
log_file = ['{}: {}'.format(job, file_name.replace("/", "\\"))]
log_file_info.append(log_file)
return log_file_info
预期结果:
[[''project_name1:\ network_location \ folder \ subfolder1 \ subfolder2 \ subfolder3 \ Jenkins_Build \ buildlog \ windows \ project_name1_2018-10-24.txt'], ['project_name2:\ network_location \ folder \ subfolder1 \ subfolder2 \ subfolder3 \ Jenkins_Build \ buildlog \ windows \ project_name2_2018-10-24.txt'], ['project_name3:\ network_location \ folder \ subfolder1 \ subfolder2 \ subfolder3 \ Jenkins_Build \ buildlog \ windows \ project_name3_2018-10-24.txt']]
实际结果:
[[''project_name1:\\\\ network_location \\ folder \\ subfolder1 \\ subfolder2 \\ subfolder3 \\ Jenkins_Build \\ buildlog \\ windows \\ project_name1_2018-10-24.txt'], ['project_name2:\\\\ network_location \\ folder \\ subfolder1 \\ subfolder2 \\ subfolder3 \\ Jenkins_Build \\ buildlog \\ windows \\ project_name2_2018-10-24.txt'],
['project_name3:\\\\ network_location \\ folder \\ subfolder1 \\ subfolder2 \\ subfolder3 \\ Jenkins_Build \\ buildlog \\ windows \\ project_name3_2018-10-24.txt']]
答案 0 :(得分:3)
您的实际结果是可以的。 Python使用两个反斜杠(\\)来转义反斜杠字符。尝试使用打印功能显示结果,您会发现它实际上与您想要的相符。
>>> print[0]["project_name1"]
答案 1 :(得分:0)
我认为以下代码对您有用:
from pathlib import Path
job_list = ['project_name1', 'project_name2', 'project_name3']
def create_log_file(job_list):
log_file_info = []
for job in job_list:
file_name = os.path.join('\\network_location\\folder\\subfolder1\\subfolder2\\subfolder3\\Jenkins_Build\\buildlog\\windows\\', job + "_" + current_date + file_format)
file_content = get_console_output(job)
with open(file_name, 'w', encoding="utf-8") as f:
f.write(file_content)
log_file = ['{}: {}'.format(job, Path(file_name))]
log_file_info.append(log_file)
return log_file_info
print(create_log_file(job_list))
请注意开头的导入声明。使用Path(file_name)时,您要告诉解释器将给定的字符串显式视为路径。
另外,我还删除了.format
语句,并用转义的反斜杠更改了所有斜杠。
有关python路径的更多信息,您可以查看以下文章: