python 代码生成器_如何为VS代码创建Python类生成器

news/2024/7/5 19:28:18

python 代码生成器

介绍 (Introduction)

If you hate stubbing out Python classes, here’s how you can create an extension in Visual Studio Code to do it for you. In this article, you’ll see how to create that extension. We will use several techniques to do so.

如果您不想混入Python类,可以按照以下方法在Visual Studio Code中创建扩展来为您完成。 在本文中,您将看到如何创建该扩展。 我们将使用几种技术来做到这一点。

  • Prompting User Input

    提示用户输入
  • Array Map and Join Functions

    数组映射和联接函数
  • ES6 Template Literals

    ES6模板文字
  • Writing to the File System

    写入文件系统

You’ll create a new extension, prompt the user for input, convert the input to a string that represents the new class file, and write out the result.

您将创建一个新扩展名,提示用户输入,将输入转换为代表新类文件的字符串,然后写出结果。

创建项目 (Creating the Project)

To get started with developing Code extensions, you’ll need two different NPM packages installed, “yo” and “generator-code”.

要开始开发Code扩展,您需要安装两个不同的NPM软件包,“ yo”和“ generator-code”。

To generate your project, run the following command.

要生成您的项目,请运行以下命令。

yo code

This will follow up by asking you several questions about your project. Choose either JavaScript or TypeScript for your extension.

接下来,将询问您有关项目的几个问题。 为扩展名选择JavaScript或TypeScript。

After answering all of the questions, open the newly created project in VS Code.

回答完所有问题后,用VS Code打开新创建的项目。

You’ll have a several different files created for you, the two most important are the package.json and extension.js files.

您将为您创建几个不同的文件,其中两个最重要的是package.jsonextension.js文件。

Start by opening the extension.js file. Then, rename the extension command name to createPyClass.

首先打开extension.js文件。 然后,将扩展命令名称重命名为createPyClass

Then, in the package.json file, rename the activation event and command to match the name of the command.

然后,在package.json文件中,重命名激活事件和命令以匹配命令的名称。

Update the title as well, which is what the user will type to activate the command.

同时更新标题,这是用户键入以激活命令的内容。

To run the extension, open the debug panel (looks like a bug) and press play. This will open up a new instance of VS Code. Open the command prompt (Command+Shift+P on Mac and Control+Shift+P on Windows) and type “Create Python Class”.

要运行扩展,请打开调试面板(看起来像个错误),然后按play。 这将打开一个新的VS Code实例。 打开命令提示符(在Mac上为Command + Shift + P ,在Windows上为Control + Shift + P ),然后键入“创建Python类”。

And you should see the “Hello World” message.

并且您应该看到“ Hello World”消息。

提示用户输入 (Prompt the User for Input)

We need to prompt the user for input about the class (class name and properties) and convert that input into a string that we can write to the new class file.

我们需要提示用户输入有关类的信息(类名称和属性),并将该输入转换为可写入新类文件的字符串。

Let’s start by ensuring the user has a folder currently open. If not, we don’t have a place to write the new class file to. If the user does not have a folder open, we show an error message and return.

首先,确保用户具有当前打开的文件夹。 如果没有,我们没有地方要写入新的类文件。 如果用户没有打开文件夹,我们将显示错误消息并返回。

if (!vscode.workspace.workspaceFolders) {
  return vscode.window.showErrorMessage(
    "Please open a directory before creating a class."
  );
}

Now, we can ask the user for the name of the class they want to create. If the user, for some reason, closes the input prompt (by hitting escape) we return.

现在,我们可以向用户询问他们要创建的类的名称。 如果用户由于某种原因关闭了输入提示(通过按Escape键),我们将返回。

const className = await vscode.window.showInputBox({
  prompt: "Class Name?"
});

if (!className) return;

We want to let the user input as many properties as they want to. For this we prompt initially for a property, then run a while loop retrieving properties until the user enters “done”.

我们想让用户输入想要的尽可能多的属性。 为此,我们首先提示输入属性,然后运行while循环以检索属性,直到用户输入“ done”为止。

let count = 1;
let property = await vscode.window.showInputBox({
  prompt: `Property #${count}? ('done' when finished)`
});
const properties = [];
while (property != "done") {
  properties.push(property);
  count++;
  property = await vscode.window.showInputBox({
    prompt: `Property #${count}? ('done' when finished)`
  });
}

Rerun your extension, enter in valid inputs, and print the user’s info to be sure it looks right.

重新运行您的扩展程序,输入有效的输入,然后打印用户的信息以确保它看起来正确。

创建类内容字符串 (Create the Class Content String)

Now, we start to take the user’s input to generate the content of the class. Let’s start by creating the class definition line as well as the constructor definition.

现在,我们开始接受用户的输入以生成类的内容。 让我们从创建类定义行以及构造函数定义开始。

const classDefinition = `class ${className}:`;
const constructorDefinition = `def __init__(self, ${properties.join(", ")}):`;

Then, we can create the constructor assignments lines. This is where the user will initialize variables on itself, using the values of the constructor parameters. For this, we use map (as we will from now on) to convert each of the property inputs in some way.

然后,我们可以创建构造函数分配行。 用户可以在此处使用构造函数参数的值自行初始化变量。 为此,我们将使用map (从现在开始将使用)以某种方式转换每个属性输入。

const constructorAssignments = properties
  .map(property => `self.${property} = ${property}\n\t\t`)
  .join("");

Now, for each property, we create a getter function. Again, we use map to convert each property into a string that represents its getter.

现在,对于每个属性,我们创建一个getter函数。 同样,我们使用map将每个属性转换为代表其getter的字符串。

const classGetters = properties
  .map(
    property => `\tdef get_${property}(self):\n\t\treturn self.${property}\n\n`
  )
  .join("");

The last thing we want to create is the string function that will tell Python how to print this object. Again, we use the map function to convert each property by printing the name of the property and then its value.

我们要创建的最后一件事是字符串函数,它将告诉Python如何打印此对象。 同样,我们使用map函数通过打印属性的名称和其值来转换每个属性。

Notice that in the map return value, we are adding a comma and a plus. This means for the last property, we would be adding unnecessary characters at the end. For this reason, we convert the resulting array to a string and chop off the last 11 characters by using splice.

注意,在地图返回值中,我们添加了一个逗号和一个加号。 这意味着对于最后一个属性,我们将在末尾添加不必要的字符。 因此,我们将结果数组转换为字符串,并使用splice切掉最后11个字符。

const dunderStrString = `\tdef __str__():\n \t\treturn ${properties
  .map(property => '"' + property + ': "' + " + " + property + ' + " , " + ')
  .join("")
  .slice(0, -11)}`;

Let’s take this individual pieces and put them all together!

让我们把这些单独的部分放在一起!

const classString = `${classDefinition}
    ${constructorDefinition}
        ${constructorAssignments}
${classGetters}
${dunderStrString}`;

Create a log statement and run this again to make sure your class string looks good.

创建一个日志语句,然后再次运行它,以确保您的类字符串看起来不错。

创建类文件 (Creating the Class File)

Now, we need to write that string to a new file. To work with files, we need to import the “fs” and “path” modules from Node at the top of the page.

现在,我们需要将该字符串写入新文件。 要使用文件,我们需要从页面顶部的Node导入“ fs”和“ path”模块。

const fs = require("fs");
const path = require("path");

Then, we need to get the path for the user’s currently open directory. You can get a reference to open directories by vscode.workspace.workspaceFolders. Then, we get the first one from the resulting array, grab its URI, and convert it to a string. The resulting path string included a prefix, so we strip that out by splitting on a colon and grabbing what comes after the colon.

然后,我们需要获取用户当前打开目录的路径。 您可以通过vscode.workspace.workspaceFolders获得对打开目录的vscode.workspace.workspaceFolders 。 然后,我们从结果数组中获得第一个,获取其URI,并将其转换为字符串。 生成的路径字符串包含前缀,因此我们通过在冒号上分割并抓住冒号后面的内容来去除前缀。

const folderPath = vscode.workspace.workspaceFolders[0].uri
  .toString()
  .split(":")[1];

Now we can use the fs module, the folder path, and the name of the class file, to write the class string to our new file.

现在,我们可以使用fs模块,文件夹路径和类文件的名称,将类字符串写入新文件。

fs.writeFile(path.join(folderPath, `${className}.py`), classString, err => {});

We can take it one step further by providing the user some feedback based on whether or not the write file was successful.

通过根据写入文件是否成功为用户提供一些反馈,我们可以进一步向前迈进。

fs.writeFile(path.join(folderPath, `${className}.py`), classString, err => {
  if (err) {
    vscode.window.showErrorMessage("Something went wrong");
    return console.log(err);
  }
  vscode.window.showInformationMessage(`${className} Class created.`);
});

运行 (Run It)

Either refresh your debugging instance or start again by following the steps above. With the debug instance of VS Code open, run your “Create Python Class” command again. Then, enter the name of the class you want to create. “Person” in this case.

刷新调试实例,或者按照上述步骤重新开始。 在VS Code的调试实例打开的情况下,再次运行“创建Python类”命令。 然后,输入要创建的类的名称。 在这种情况下为“人”。

Then enter your properties, “name” first.

然后输入您的属性,“名称”。

Then “age”.

然后是“年龄”。

Then “done” to finish.

然后“完成”以完成。

The file is successfully created.

文件创建成功。

Then, double check your file was actually created and it looks good

然后,仔细检查您的文件是否实际创建,看起来不错

结论 (Conclusion)

In this tutorial, you’ve created an extension to solve a specific problem. It provides an opportunity to learn more about VS Code, and it’s also something that others will benefit from.

在本教程中,您已经创建了扩展程序来解决特定问题。 它提供了一个学习VS Code的机会,这也是其他人将从中受益的东西。

翻译自: https://www.digitalocean.com/community/tutorials/creating-a-python-class-generator-for-vs-code

python 代码生成器


http://www.niftyadmin.cn/n/3649350.html

相关文章

[C#]如何将自定义的structure转换为byte[]?

如何将自定义的structure转换为byte[]?整理者:郑昀UltraPower示例如下:using System.Runtime.InteropServices;public static byte[] RawSerialize( object anything ){int rawsize Marshal.SizeOf( anything );IntPtr buffer Marshal.Allo…

在Node.js中使用服务器发送的事件来构建实时应用

The goal of this article is to present a complete solution for both the back-end and front-end to handle realtime information flowing from server to client. 本文的目的是为后端和前端提供一个完整的解决方案,以处理从服务器到客户端的实时信息流。 The…

鼠标点击页面出现富强自由等文字JS特效

在其他博客看到一款JS特效,感觉很不错,所有网上收集过来分享给大家。 效果参考本网站,添加点击特效,点击页面会显示: 富强, 民主, 文明, 和谐, 自由, 平等,公正 ,法治, 爱国, 敬业, 诚信, 友善 把以下代码添加到当前…

统一应用程序中所有Activity的栈管理

public class ActivityManager {//单例模式&#xff1a;饿汉式private ActivityManager(){}private static ActivityManager activityManager new ActivityManager();public static ActivityManager getInstance(){return activityManager;}//提供栈的对象private Stack<Ac…

[dotNET]“ThreadPool 对象中没有足够的自由线程来完成操作”的现象和解决办法

“ThreadPool 对象中没有足够的自由线程来完成操作”的现象和解决办法Ultrapower 20050406其实微软有一篇《异步 HttpWebRequest、接口实现及其他》对此种现象解释得非常清楚&#xff0c;我这边只是做一个笔记。最常见的就是使用HttpWebRequest的时候&#xff0c;调用Send方法出…

Android工程师一定要知道的国内应用市场汇总

2010年在国内出现了Android系统智能机的大规模发展&#xff0c;而应用商城也在火拼起来&#xff0c;下面我推荐一下国内Android的免费软件商城。 应用汇 掌上应用汇是一款基于Android系统的本土化软件市场&#xff0c;掌上应用汇团队致力于为中国用户打造最全面&#xff0c;最…

debian 10 安装_如何在Debian 10上安装和使用ClickHouse

debian 10 安装介绍 (Introduction) ClickHouse is an open-source, column-oriented analytics database created by Yandex for OLAP and big data use cases. ClickHouse’s support for real-time query processing makes it suitable for applications that require sub-s…

虚拟机安装Kali Linux操作系统

▣ 博主主站地址&#xff1a;微笑涛声 【www.cztcms.cn】 Kali Linux是基于Debian的Linux发行版&#xff0c; 设计用于数字取证操作系统。每一季度更新一次。由Offensive Security Ltd维护和资助。最先由Offensive Security的Mati Aharoni和Devon Kearns通过重写BackTrack来完成…