英文:
Pycharm + Black with Formatting on Auto-save by Running a Script
问题
我正在尝试编写一个Python脚本,该脚本将安装Black(代码格式化工具),并在Pycharm设置中进行更改,以在自动保存时运行Black并将其添加到外部工具(我正在使用Linux)。我不知道如何开始,以及要编写什么样的代码。
对于我的本地机器,我手动操作,但需要不手动操作并运行脚本,让它执行所有所需步骤。由于参与项目的不仅仅是我一个人,我们所有人都需要具有相同的格式配置,因此需要编写一个Python脚本来实现。
英文:
I am trying to write a Python script that will install Black(code formatter), and do changes in Pycharm settings to run Black on Autosave and add it to external tools(I am using Linux). I didn't know how to start, and what kind of code to write.
For my local machine, I do it manually, but needed to not do it manually and run the script and it does all the needed steps. As people working on the project not only me, we all need to have the same formatting configurations, so need to have a python script for that.
答案1
得分: 1
你可以通过更新PyCharm中工具的XML文件并添加所需的工具来实现。
以下是Python中的函数:
import xml.etree.ElementTree as ET
def add_external_tool(tool_name, command):
your_version = "2023.1.2" # 请将您的PyCharm版本放在这里
# 工具的tools.xml文件路径
tools_file = fr"~/.PyCharm{your_version}/config/tools/tools.xml"
# 加载XML文件
tree = ET.parse(tools_file)
root = tree.getroot()
# 创建一个新的 <tool> 元素
tool = ET.SubElement(root, 'tool')
tool.set('name', tool_name)
tool.set('description', 'My custom tool') # 工具的描述
# 创建带有命令的 <exec> 元素
exec_element = ET.SubElement(tool, 'exec') # 根据您的需求更改
exec_element.text = command
# 将修改后的XML保存回文件
tree.write(tools_file)
# 使用示例
add_external_tool('black', 'which black')
您可以根据需要修改代码以获取有关如何设置 black 格式化程序 的更多信息。
英文:
You can do it with update xml file of tools in pycharm, and add tool you want.
> Here is function in python
import xml.etree.ElementTree as ET
def add_external_tool(tool_name, command):
your_version = "2023.1.2" # Put your pycharm version here
# Path to the tools.xml file
tools_file = fr"~/.PyCharm{your_version}/config/tools/tools.xml"
# Load the XML file
tree = ET.parse(tools_file)
root = tree.getroot()
# Create a new <tool> element
tool = ET.SubElement(root, 'tool')
tool.set('name', tool_name)
tool.set('description', 'My custom tool') # Your description for tool
# Create the <exec> element with the command
exec_element = ET.SubElement(tool, 'exec') # Change it as you want
exec_element.text = command
# Save the modified XML back to the file
tree.write(tools_file)
# Usage
add_external_tool('black', 'which black')
you can modify code as you want was reading to get more information on how to setup black formatter
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论