格式化xml需要用到库:xml.dom.minidom
直接上代码:
import sys, os
import xml.etree.ElementTree as ET
from xml.dom import minidom
TOOL_NAME = 'ResCheck'
PYTHON = sys.argv[1]
CUSTOM_TOOL_FILE = sys.argv[2] #文件路径
is_empty = True
if os.path.isfile(CUSTOM_TOOL_FILE):
is_empty = os.path.getsize(CUSTOM_TOOL_FILE) == 0
if is_empty:
f = open(CUSTOM_TOOL_FILE, 'w')
# f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
# f.write('<!--perforce-xml-version=1.0-->')
f.write('<CustomToolDefList varName="customtooldeflist"/>')
f.close()
tree = ET.parse(CUSTOM_TOOL_FILE)
for name in tree.getroot().iter('Name'):
if name.text == TOOL_NAME:
print('ResCheck tool is already set up.')
sys.exit()
custom_tool_def = ET.SubElement(tree.getroot(), 'CustomToolDef')
definition = ET.SubElement(custom_tool_def, 'Definition')
name = ET.SubElement(definition, 'Name')
name.text = TOOL_NAME
command = ET.SubElement(definition, 'Command')
command.text = PYTHON
arguments = ET.SubElement(definition, 'Arguments')
arguments.text = 'filesCheck.py %p $r $c $u $p'
shortcut = ET.SubElement(definition, 'Shortcut')
init_dir = ET.SubElement(definition, 'InitDir')
init_dir.text = sys.argv[3]
xmlstr = minidom.parseString(ET.tostring(tree.getroot())).toprettyxml(indent=' ')
xml_pretty_str = xml.toprettyxml()
with open(CUSTOM_TOOL_FILE, 'w') as f:
f.write(xmlstr)
print('filesCheck tool has been set up successfully.')
亲测可用,希望能给您一些帮助
|