├── .eslintrc.json
├── .gitignore
├── .vscode
├── extensions.json
├── launch.json
├── settings.json
└── tasks.json
├── .vscodeignore
├── CHANGELOG.md
├── README.md
├── images
├── Ctl+Shift+;.gif
├── Ctl+Shift+L-NOselection.gif
├── Ctl+Shift+L-NOvariable.gif
├── Ctl+Shift+L-selection.gif
├── Ctl+Shift+O.gif
├── Ctl+Shift+R.gif
├── Ctl+Shift+T.gif
├── Ctl+Shift+down.gif
├── Ctl+Shift+forwardslash.gif
├── Ctl+Shift+up.gif
├── Multiple_variables.gif
├── color-text.gif
├── donation.png
├── execution.gif
├── icon-128.png
├── installanotherversion.png
├── setting1.png
└── setting2.png
├── package.json
├── src
├── extension.ts
└── test
│ ├── runTest.ts
│ └── suite
│ ├── extension.test.ts
│ └── index.ts
├── test
├── .vscode
│ └── settings.json
├── demo-gif.py
├── demo.py
├── no_dl.py
└── test.py
└── tsconfig.json
/.eslintrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "root": true,
3 | "parser": "@typescript-eslint/parser",
4 | "parserOptions": {
5 | "ecmaVersion": 6,
6 | "sourceType": "module"
7 | },
8 | "plugins": [
9 | "@typescript-eslint"
10 | ],
11 | "rules": {
12 | "@typescript-eslint/naming-convention": "warn",
13 | "@typescript-eslint/semi": "warn",
14 | "curly": "warn",
15 | "eqeqeq": "warn",
16 | "no-throw-literal": "warn",
17 | "semi": "off"
18 | },
19 | "ignorePatterns": [
20 | "out",
21 | "dist",
22 | "**/*.d.ts"
23 | ]
24 | }
25 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | out
2 | dist
3 | node_modules
4 | .vscode-test/
5 | *.vsix
6 | package-lock.json
--------------------------------------------------------------------------------
/.vscode/extensions.json:
--------------------------------------------------------------------------------
1 | {
2 | // See http://go.microsoft.com/fwlink/?LinkId=827846
3 | // for the documentation about the extensions.json format
4 | "recommendations": [
5 | "dbaeumer.vscode-eslint"
6 | ]
7 | }
8 |
--------------------------------------------------------------------------------
/.vscode/launch.json:
--------------------------------------------------------------------------------
1 | // A launch configuration that compiles the extension and then opens it inside a new window
2 | // Use IntelliSense to learn about possible attributes.
3 | // Hover to view descriptions of existing attributes.
4 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
5 | {
6 | "version": "0.2.0",
7 | "configurations": [
8 | {
9 | "name": "Run Extension",
10 | "type": "extensionHost",
11 | "request": "launch",
12 | "args": [
13 | "--extensionDevelopmentPath=${workspaceFolder}"
14 | ],
15 | "outFiles": [
16 | "${workspaceFolder}/out/**/*.js"
17 | ],
18 | "preLaunchTask": "${defaultBuildTask}"
19 | },
20 | {
21 | "name": "Extension Tests",
22 | "type": "extensionHost",
23 | "request": "launch",
24 | "args": [
25 | "--extensionDevelopmentPath=${workspaceFolder}",
26 | "--extensionTestsPath=${workspaceFolder}/out/test/suite/index"
27 | ],
28 | "outFiles": [
29 | "${workspaceFolder}/out/test/**/*.js"
30 | ],
31 | "preLaunchTask": "${defaultBuildTask}"
32 | }
33 | ]
34 | }
35 |
--------------------------------------------------------------------------------
/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | // Place your settings in this file to overwrite default and user settings.
2 | {
3 | "files.exclude": {
4 | "out": false // set this to true to hide the "out" folder with the compiled JS files
5 | },
6 | "search.exclude": {
7 | "out": true // set this to false to include "out" folder in search results
8 | },
9 | // Turn off tsc task auto detection since we have the necessary tasks as npm scripts
10 | "typescript.tsc.autoDetect": "off"
11 | }
--------------------------------------------------------------------------------
/.vscode/tasks.json:
--------------------------------------------------------------------------------
1 | // See https://go.microsoft.com/fwlink/?LinkId=733558
2 | // for the documentation about the tasks.json format
3 | {
4 | "version": "2.0.0",
5 | "tasks": [
6 | {
7 | "type": "npm",
8 | "script": "watch",
9 | "problemMatcher": "$tsc-watch",
10 | "isBackground": true,
11 | "presentation": {
12 | "reveal": "never"
13 | },
14 | "group": {
15 | "kind": "build",
16 | "isDefault": true
17 | }
18 | }
19 | ]
20 | }
21 |
--------------------------------------------------------------------------------
/.vscodeignore:
--------------------------------------------------------------------------------
1 | .vscode/**
2 | .vscode-test/**
3 | src/**
4 | .gitignore
5 | .yarnrc
6 | vsc-extension-quickstart.md
7 | **/tsconfig.json
8 | **/.eslintrc.json
9 | **/*.map
10 | **/*.ts
11 | test/
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Change Log
2 |
3 | ## [2022/2/13]
4 | 0.1.0
5 | - Initial release
6 |
7 | ## [2022/2/14]
8 | 0.1.1
9 | - Add shortcut `Ctrl+Shift+T` to print `type(variable)`, also you can change `type()` to other built-in function in extension settings.
10 |
11 | ## [2022/2/15]
12 | 0.1.2
13 | - Downward compatible to vscode version 1.63.0.
14 | - When insert simply `print()`, if current line is not empty, insert at next line, or just insert in current line.
15 | - Add introduction video link.
16 |
17 | ## [2022/2/16]
18 | 0.1.3
19 | - Able to output colored text in terminal by using python built-in package: `termcolor`.
20 | - Add the ability to automatically recognize variable before `+=`.
21 |
22 | ## [2022/2/19]
23 | 0.1.4
24 | - Downward compatible to vscode version 1.57.0.
25 | - Fix a bug when inserting with selection and `Ctrl+Shift+T`.
26 | - Monitor the change of configuration and make it take effect immediately, so you don't need to restart vscode.
27 |
28 | ## [2022/2/19]
29 | 0.1.5
30 | - Trim space besides selected variable.
31 |
32 | ## [2022/2/27]
33 | 0.1.6
34 | - If selected variable is new defined for the first time, insert code at current line.
35 | - If select multiple lines of code, press `Ctrl+Shift+/` will only comment out print statements inside the selected scope instead of all of print statements in the file. The same to `Ctrl+Shift+R`.
36 | - `Ctrl+Shift+/` can both comment and uncomment print statement depend whether the print statement have `# ` or not.
37 | - Add new shortcut:`Ctrl+Shift+;` which will insert `print("".center(50, "-"))` used for printing separator line.
38 | - `Ctrl+Shift+R` will delete entire line, not just clean the content of the line, and it can recognize those code which start with `print(`, `# print(`,`prints(`,`# prints(` and delete them.
39 |
40 | ## [2022/4/2]
41 | 0.1.7
42 | - Add the ability to recognize variables that were uppacked from tuple,list etc.
43 | - Change the default operation of `ctrl shift /` without selection from toggle comment to comment out all of those uncomment print statements.
44 | - Allow user to set customized suffix, like`:\n` by default.
45 |
46 | ## [2022/4/5]
47 | 0.1.8
48 | - Fix a bug of recognizing unpacked variables.
49 | - Change the default suffix from `:\n` to `: `.
50 | - Fix a bug when pressing `Ctrl Shift ;`.
51 |
52 | ## [2022/4/9]
53 | 0.1.9
54 | - Fix a bug of recognizing variable when there are multiple `=` in a line.
55 |
56 | ## [2023/4/13]
57 | 0.2.0
58 | - Use the "[formatted string literals](https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals)" feature introduced since python 3.6.
59 |
60 | ## [2023/4/14]
61 | 0.2.1
62 | - Update README.md
63 |
64 | ## [2023/10/1]
65 | 0.3.0
66 | - To support python built-in `logging`, `loguru`, `pprint` more friendly, now users can set the print funtion and option of wheather to use formatted string.
67 | - Fix bug of toggle comment out when selection is empty
68 |
69 | ## [2023/12/28]
70 | 0.3.1
71 | - Support select multiple lines, then process their variables one by one automatically.
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |

3 |
4 |
⚡Quick Python Print
5 | An vscode extention that can save you time 🕒 if you write python code
6 |
7 |
8 |
9 | [](https://marketplace.visualstudio.com/items?itemName=WeidaWang.quick-python-print)
10 | [](https://marketplace.visualstudio.com/items?itemName=WeidaWang.quick-python-print)
11 | [](https://marketplace.visualstudio.com/items?itemName=WeidaWang.quick-python-print)
12 |
13 | ## 📢Introduction
14 | This extension is inspired by "[Python Quick Print](https://github.com/AhadCove/Python-Quick-Print)". "Python Quick Print" can quickly print out variables like `print(f"==>> a: {a}")` on the terminal by using keyboard shortcut `Ctrl+Shift+L`, while this extension "Quick Python Print" adds some more features:
15 | ✨ You can put the cursor at target line, the extension will **automatically recognize** the variable in the line.
16 | ✨ If did not recognize any variable in current line, it will just **insert simply** `print()` and move the cursor inside the bracket.
17 | ✨ Press `Ctrl+Shift+O` to **print attribute of variable**, here is tensor `shape` by default, e.g. `print(f"==>> a.shape: {a.shape}")`.
18 | ✨ Press `Ctrl+Shift+T` to **print function of variable**, here is `type` by default, e.g. `print(f"==>> type(a): {type(a)}")`.
19 | ✨ Press `Ctrl+Shift+;` to insert `print("".center(50, "-"))` used for printing **delimiter line**.
20 | ✨ Press `Ctrl+Shift+/` to **comment out or uncomment** all print statements inside the selection or in the file.
21 | ✨ Press `Ctrl+Shift+R` to **delete** all print statements inside the selection or in the file.
22 | ✨ Support users to define **customized print function** like `logger.debug`, `pprint` other than origianl `print`.
23 | ✨ Support users to define **customized prefix and suffix** of print content flexibly in extension settings.
24 | ✨ Support printing **multiple variables separated by `,` in one line and multiple variables in multiple lines together**.
25 | ✨ Able to **output colored text** in terminal by using python built-in package: `termcolor`.
26 |
27 | If you find a bug or have feature request, you can check out the [ChangeLog](CHANGELOG.md) to see if this bug or feature had been fixed or added in the latest version, if not, please issue it in this extension's GitHub[ repo](https://github.com/wwdok/Quick-Python-Print).
28 |
29 | ## 🌟Motivation
30 |
31 | When I am learning deep learning model, I often want to know how the tensor shape changes along the way, I think this will help me understand how the deep learning model works. Take pytorh for example, these operations `view,slice,concat,permute,conv,linear` etc all will change the tensor shape. Fortunately, many deep learning framework all have `.shape` attribute of tensor(as far as I know, there are pytorch, numpy, tensorflow, paddlepaddle, oneflow), so this makes the extension be useful for different deep learning framework users. Afterwards, I add more features to make it also useful for other python developers. I know using debug is a good alternative to get the tensor shape, but I think the print function is still useful in some cases.
32 |
33 | ## 🚀Installation
34 |
35 | Before installation, make sure your vscode version ≥ 1.57.0.
36 |
37 | Because since version 0.2.0 which use the "[formatted string literals](https://docs.python.org/3/whatsnew/3.6.html#pep-498-formatted-string-literals)" feature introduced since python 3.6, if your python version < 3.6, you can install previous version (e.g. 0.1.9) by:
38 |
39 | 
40 |
41 | This extension is available in the Visual Studio Code Extension Marketplace, you can search "Quick-Python-Print" and install it.
42 |
43 | ## ✋How to use
44 |
45 | Introduction video (Chinese speech with English subtitles): [Youtube](https://www.youtube.com/watch?v=w5cd_8lzylA) | [Bilibili](https://www.bilibili.com/video/BV1hY411V7bi) (When I made this video, it was version 0.1.1, and there have been many changes in the current version).
46 |
47 | This extension only activates within `.py` and `.ipynb` files.
48 |
49 | ### ⌨️Keyboard Shortcut
50 |
51 | For Mac user, the `Ctrl` should be `Cmd`.
52 |
53 | **Note : From version 0.2.0, the inserted code will be a little different, the inserted code will be `print(f"==>> a: {a}")` instead of `print("==>> a: ", a)`.**
54 |
55 | **Ctrl+Shift+L**
56 |
57 | Select the variable, then press `Ctrl+Shift+L`, it will insert print statement at next line:
58 |
59 | 
60 |
61 | You can also just put the cursor at the target line, then the extension will **automatically recognize** the variable that before `=`, `+=`, `-=`, `/=`, `//=`, `*=`, `%=`:
62 |
63 | 
64 |
65 | This extension can also handle some little complicated cases, such as **unpacked variables separated by `,`**, and **print multiple variables in multiple lines together**:
66 |
67 | 
68 |
69 | If you didn't select variable or the extension can't recognize variable, it will simply insert `print()` and move the cursor inside it.
70 | If the selected content is exactly the content of the entire line, it will treat the selected content as a variable and insert code at the current line :
71 |
72 | 
73 |
74 | If the extension recognizes the variable wrongly, you can manually select the variable, or report this issue in GitHub repo.
75 |
76 | **Ctrl+Shift+O**
77 |
78 | `Ctl+Shift+O` is similar to `Ctrl+Shift+L` except that it will print tensor shape by default:
79 |
80 | 
81 |
82 | **Ctrl+Shift+T**
83 |
84 | `Ctl+Shift+T` is similar to above except that it will print type of variable by default:
85 |
86 | 
87 |
88 | **Ctrl+Shift+/**
89 |
90 | Comment out or uncomment the print statement in the selected scope or in the python file:
91 |
92 | 
93 |
94 | **Ctrl+Shift+Up**
95 |
96 | Comment out all print statement above the cursor in the python file:
97 |
98 | 
99 |
100 | **Ctrl+Shift+Down**
101 |
102 | Comment out all print statement below the cursor in the python file:
103 |
104 | 
105 |
106 | **Ctrl+Shift+;**
107 |
108 | Insert a print statement that will print 50 `-` to form a delimiter like `--------------------------------------------------`:
109 |
110 | 
111 |
112 | **Ctrl+Shift+R**
113 |
114 | Delete all the print statement(include those commented) in the python file or in the selected scope:
115 |
116 | 
117 |
118 | **Compatibility with different framework**
119 |
120 | Many deep learning framework all have `.shape` attribute of tensor:
121 |
122 | 
123 |
124 | If any of these shortcuts conflicts with existing shortcut, you may change it in the `Keyboard Shortcuts Setting`: Press `Cmd+P` or `Ctrl+P` and type in `>Open Keyboard Shortcuts`. Search for the conflict shortcut, then you will find those shortcut using the same keys, then right click one of them, modify or delete keybinding.
125 |
126 | ### ⚙️Extension Settings
127 |
128 | This extension has following settings:
129 |
130 | 
131 | 
132 |
133 | You can go to the `Extension Settings` to modify them to suit your preferences. After modification, it should take effect immediately.
134 |
135 | ### ❔FAQ
136 |
137 | * How to use with loguru logger or logging logger ?
138 | - see this [issue](https://github.com/wwdok/Quick-Python-Print/issues/2).
139 |
140 | * How to use with pprint ?
141 | - see this [issue](https://github.com/wwdok/Quick-Python-Print/issues/3).
142 |
143 | ### 🌈Color output text
144 | To color the output text in terminal, you need to do these things:
145 | 1. Go to `Extension Settings`, check the `5.enable-colored-output-text` to be true. And you can select the color you like from the drop-down list.
146 | 2. Add `from termcolor import colored` in the python file
147 | 3. Now Press `Ctrl+Shift+L` or `Ctrl+Shift+O` or `Ctrl+Shift+T` will insert the print statement that can color output text.
148 | 4. Run Python File in Terminal.
149 |
150 | 
151 |
152 | ## 🔗pypi package
153 | I also make a pypi package : [printensor](https://github.com/wwdok/print_tensor) to uppack tensors inside list, tuple, dict, generator, then print their tensor shape. After installing and import, you can replace `print(` with `prints(` to intergrate it with this extension.
154 |
155 | ## 💬Known issue
156 | This extension can not handle tensor that cross multiple lines, for example:
157 | ```
158 | a = torch.tensor([[1.0, 2.0, 3.0],
159 | [4.0, 5.0, 6.0]])
160 | ```
161 | You can use `Alt + down` to move down the inserted print statement.
162 |
163 | ## ⚠Warning
164 | This extension uses Python 3 syntax, if you're using Python 2 print isn't a function. You can import this behavior from `__future__`:
165 | `from __future__ import print_function`
166 |
167 | ## 💗Donation
168 | If you find this extension can help you save time, and willing to donate me, I would be very grateful ! ❤
169 |
170 | 🥤[Buy me a Coca-Cola](https://ko-fi.com/weidawang)
171 |
172 |
173 |
174 | ## 📃License
175 | MIT License
176 |
--------------------------------------------------------------------------------
/images/Ctl+Shift+;.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/Ctl+Shift+;.gif
--------------------------------------------------------------------------------
/images/Ctl+Shift+L-NOselection.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/Ctl+Shift+L-NOselection.gif
--------------------------------------------------------------------------------
/images/Ctl+Shift+L-NOvariable.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/Ctl+Shift+L-NOvariable.gif
--------------------------------------------------------------------------------
/images/Ctl+Shift+L-selection.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/Ctl+Shift+L-selection.gif
--------------------------------------------------------------------------------
/images/Ctl+Shift+O.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/Ctl+Shift+O.gif
--------------------------------------------------------------------------------
/images/Ctl+Shift+R.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/Ctl+Shift+R.gif
--------------------------------------------------------------------------------
/images/Ctl+Shift+T.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/Ctl+Shift+T.gif
--------------------------------------------------------------------------------
/images/Ctl+Shift+down.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/Ctl+Shift+down.gif
--------------------------------------------------------------------------------
/images/Ctl+Shift+forwardslash.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/Ctl+Shift+forwardslash.gif
--------------------------------------------------------------------------------
/images/Ctl+Shift+up.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/Ctl+Shift+up.gif
--------------------------------------------------------------------------------
/images/Multiple_variables.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/Multiple_variables.gif
--------------------------------------------------------------------------------
/images/color-text.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/color-text.gif
--------------------------------------------------------------------------------
/images/donation.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/donation.png
--------------------------------------------------------------------------------
/images/execution.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/execution.gif
--------------------------------------------------------------------------------
/images/icon-128.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/icon-128.png
--------------------------------------------------------------------------------
/images/installanotherversion.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/installanotherversion.png
--------------------------------------------------------------------------------
/images/setting1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/setting1.png
--------------------------------------------------------------------------------
/images/setting2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/wwdok/Quick-Python-Print/b896a991a46e02132ce254ca18f3a4b70e02ffa2/images/setting2.png
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "quick-python-print",
3 | "displayName": "Quick-Python-Print",
4 | "description": "Quickly handle print operations : Insertion(include print out variable, its attribute and function etc), (Un)comment, Delete by using shortcuts",
5 | "version": "0.3.1",
6 | "publisher": "WeidaWang",
7 | "author": {
8 | "name": "Weida Wang"
9 | },
10 | "repository": {
11 | "type": "git",
12 | "url": "https://github.com/wwdok/Quick-Python-Print"
13 | },
14 | "icon": "images/icon-128.png",
15 | "engines": {
16 | "vscode": "^1.57.0"
17 | },
18 | "categories": [
19 | "Programming Languages",
20 | "Debuggers",
21 | "Machine Learning",
22 | "Data Science"
23 | ],
24 | "keywords": [
25 | "python",
26 | "print",
27 | "tensor",
28 | "pytorch",
29 | "tensoflow",
30 | "paddlepaddle",
31 | "numpy"
32 | ],
33 | "activationEvents": [
34 | "onLanguage:python",
35 | "onCommand:extension.python-print"
36 | ],
37 | "main": "./out/extension.js",
38 | "contributes": {
39 | "languages": [
40 | {
41 | "id": "python",
42 | "aliases": [
43 | "Python",
44 | "Python3"
45 | ],
46 | "extensions": [
47 | ".py"
48 | ]
49 | }
50 | ],
51 | "commands": [
52 | {
53 | "command": "extension.python-print",
54 | "title": "Print variable purely"
55 | },
56 | {
57 | "command": "extension.python-print-tensor-shape",
58 | "title": "Print (Pytorch, TensorFlow, PaddlePaddle, Numpy) tensor shape by default"
59 | },
60 | {
61 | "command": "extension.python-print-function",
62 | "title": "Print type of variable by default"
63 | },
64 | {
65 | "command": "extension.python-print-commentall",
66 | "title": "Comment out all print statements in the scope"
67 | },
68 | {
69 | "command": "extension.python-print-commentup",
70 | "title": "Comment out all print statements above the cursor"
71 | },
72 | {
73 | "command": "extension.python-print-commentdown",
74 | "title": "Comment out all print statements below the cursor"
75 | },
76 | {
77 | "command": "extension.python-print-deleteall",
78 | "title": "Delete all print statements in the scope"
79 | },
80 | {
81 | "command": "extension.python-print-delimiter",
82 | "title": "Add delimiter line"
83 | }
84 | ],
85 | "keybindings": [
86 | {
87 | "command": "extension.python-print",
88 | "key": "ctrl+shift+l",
89 | "mac": "cmd+shift+l",
90 | "when": "editorTextFocus"
91 | },
92 | {
93 | "command": "extension.python-print-tensor-shape",
94 | "key": "ctrl+shift+o",
95 | "mac": "cmd+shift+o",
96 | "when": "editorTextFocus"
97 | },
98 | {
99 | "command": "extension.python-print-function",
100 | "key": "ctrl+shift+t",
101 | "mac": "cmd+shift+t",
102 | "when": "editorTextFocus"
103 | },
104 | {
105 | "command": "extension.python-print-commentall",
106 | "key": "ctrl+shift+/",
107 | "mac": "cmd+shift+/",
108 | "when": "editorTextFocus"
109 | },
110 | {
111 | "command": "extension.python-print-commentup",
112 | "key": "ctrl+shift+up",
113 | "mac": "cmd+shift+up",
114 | "when": "editorTextFocus"
115 | },
116 | {
117 | "command": "extension.python-print-commentdown",
118 | "key": "ctrl+shift+down",
119 | "mac": "cmd+shift+down",
120 | "when": "editorTextFocus"
121 | },
122 | {
123 | "command": "extension.python-print-deleteall",
124 | "key": "ctrl+shift+r",
125 | "mac": "cmd+shift+r",
126 | "when": "editorTextFocus"
127 | },
128 | {
129 | "command": "extension.python-print-delimiter",
130 | "key": "ctrl+shift+;",
131 | "mac": "cmd+shift+;",
132 | "when": "editorTextFocus"
133 | }
134 | ],
135 | "configuration": {
136 | "type": "object",
137 | "title": "quick python print configuration",
138 | "properties": {
139 | "0.print function": {
140 | "type": "string",
141 | "default": "print",
142 | "description": "use the python built-in print function by default, you can change it to `logger.debug` or `pprint` etc,"
143 | },
144 | "1.enable formatted string": {
145 | "type": "boolean",
146 | "default": true,
147 | "description": "if disable this checkbox, the inserted code will simply be `print(variable)`, and the following settings will not take effect"
148 | },
149 | "2.prefix": {
150 | "type": "string",
151 | "default": "==>> ",
152 | "description": "prefix before the variable name"
153 | },
154 | "3.suffix": {
155 | "type": "string",
156 | "default": ": ",
157 | "description": "suffix after the variable name, e.g. :\\n"
158 | },
159 | "4.1.attribute1": {
160 | "type": "string",
161 | "default": "",
162 | "description": "variable attribute for Ctrl+Shift+L shortcut"
163 | },
164 | "4.2.attribute2": {
165 | "type": "string",
166 | "default": ".shape",
167 | "description": "variable attribute for Ctrl+Shift+O shortcut"
168 | },
169 | "5.function": {
170 | "type": "string",
171 | "default": "type",
172 | "description": "funtion that can pass in variable for Ctrl+Shift+T shortcut"
173 | },
174 | "6.1.enable colored output text": {
175 | "type": "boolean",
176 | "default": false,
177 | "description": "whether to enable color output text."
178 | },
179 | "6.2.color for ctrl shift l": {
180 | "type": "string",
181 | "default": "green",
182 | "description": "color of output text for Ctrl+Shift+L shortcut",
183 | "enum": [
184 | "red",
185 | "green",
186 | "yellow",
187 | "blue",
188 | "magenta",
189 | "cyan",
190 | "white"
191 | ]
192 | },
193 | "6.3.color for ctrl shift o": {
194 | "type": "string",
195 | "default": "yellow",
196 | "description": "color of output text for Ctrl+Shift+O shortcut",
197 | "enum": [
198 | "red",
199 | "green",
200 | "yellow",
201 | "blue",
202 | "magenta",
203 | "cyan",
204 | "white"
205 | ]
206 | },
207 | "6.4.color for ctrl shift t": {
208 | "type": "string",
209 | "default": "blue",
210 | "description": "color of output text for Ctrl+Shift+T shortcut",
211 | "enum": [
212 | "red",
213 | "green",
214 | "yellow",
215 | "blue",
216 | "magenta",
217 | "cyan",
218 | "white"
219 | ]
220 | },
221 | "7.1.delimiter symbol for ctrl shift ;": {
222 | "type": "string",
223 | "default": "-",
224 | "description": "delimiter symbol for Ctrl+Shift+; shortcut"
225 | },
226 | "7.2.delimiter length for ctrl shift ;": {
227 | "type": "number",
228 | "default": 50,
229 | "description": "number of delimiter symbol for Ctrl+Shift+; shortcut"
230 | },
231 | "7.3.delimiter color for ctrl shift ;": {
232 | "type": "string",
233 | "default": "white",
234 | "description": "color of output text for Ctrl+Shift+; shortcut",
235 | "enum": [
236 | "red",
237 | "green",
238 | "yellow",
239 | "blue",
240 | "magenta",
241 | "cyan",
242 | "white"
243 | ]
244 | }
245 | }
246 | }
247 | },
248 | "scripts": {
249 | "vscode:prepublish": "npm run compile",
250 | "compile": "tsc -p ./",
251 | "watch": "tsc -watch -p ./",
252 | "pretest": "npm run compile && npm run lint",
253 | "lint": "eslint src --ext ts",
254 | "test": "node ./out/test/runTest.js"
255 | },
256 | "devDependencies": {
257 | "@vscode/test-electron": "^2.3.0",
258 | "@types/vscode": "^1.57.0",
259 | "@types/node": "14.x",
260 | "@types/jest": "^29.4.0",
261 | "@types/mocha": "^10.0.1",
262 | "@types/glob": "^8.1.0",
263 | "@typescript-eslint/eslint-plugin": "^5.9.1",
264 | "@typescript-eslint/parser": "^5.9.1",
265 | "eslint": "^8.6.0",
266 | "typescript": "^4.5.4"
267 | }
268 | }
269 |
--------------------------------------------------------------------------------
/src/extension.ts:
--------------------------------------------------------------------------------
1 | 'use strict';
2 | import * as vscode from 'vscode';
3 |
4 | function getInsertCode(printfunction:string, usefstring:boolean, mode:number, variableName:string, prefix:string, suffix:string, attr:string, color?:string) {
5 | let codeToInsert = '';
6 | if (usefstring){
7 | if (mode === 0) { // design for ctrl shift o
8 | if(color) {
9 | codeToInsert = `${printfunction}(colored(f"${prefix}${variableName}${attr}${suffix}{${variableName}${attr}}", "${color}"))`;
10 | } else {
11 | codeToInsert = `${printfunction}(f"${prefix}${variableName}${attr}${suffix}{${variableName}${attr}}")`;
12 | }
13 | } else if (mode === 1) { // design for ctrl shift t
14 | if(color) {
15 | codeToInsert = `${printfunction}(colored(f"${prefix}${attr}(${variableName})${suffix}{${attr}(${variableName})}", "${color}"))`;
16 | } else {
17 | codeToInsert = `${printfunction}(f"${prefix}${attr}(${variableName})${suffix}{${attr}(${variableName})}")`;
18 | }
19 | }
20 | else if (mode === 2) {
21 | if(color) {
22 | codeToInsert = `${printfunction}(colored("${variableName}".center(${prefix}, "${attr}"), "${color}"))`;
23 | } else {
24 | codeToInsert = `${printfunction}("${variableName}".center(${prefix}, "${attr}"))`;
25 | }
26 | }
27 | }else{
28 | codeToInsert = `${printfunction}(${variableName})`;
29 | }
30 | return codeToInsert;
31 | }
32 |
33 | let insertCode = (text: string, moveCursor?: boolean) => {
34 | let editor = vscode.window.activeTextEditor;
35 | let selection = editor.selection;
36 | // console.log("selection.start Position:"+selection.start.line+","+selection.start.character);
37 | editor.edit((editBuilder) => editBuilder.insert(selection.start, text)).then(() => {
38 | if (moveCursor) {
39 | // After editBuilder.insert(), the cursor have moved to the end of line, then move the cursor to the destination position
40 | vscode.commands.executeCommand('cursorMove', { to: 'left' });
41 | }
42 | });
43 | };
44 |
45 | async function insertCodeInNewLine(printfunction:string, usefstring:boolean, mode:number, variableName:string, prefix:string, suffix:string, attr:string, color?:string){
46 | vscode.commands.executeCommand('editor.action.insertLineAfter')
47 | .then(() => {
48 | const codeToInsert = getInsertCode(printfunction, usefstring, mode, variableName.trim(), prefix, suffix, attr, color);
49 | insertCode(codeToInsert);
50 | });
51 | };
52 |
53 | async function handleInsertion(printfunction:string, usefstring:boolean, prefix:string, suffix:string, attr:string, mode:number, color?:string) {
54 | let editor = vscode.window.activeTextEditor;
55 | if (!editor) {
56 | vscode.window.showErrorMessage('Can\'t insert print() because no python file is opened or cursor is not focused');
57 | return;
58 | }
59 | let selection = editor.selection;
60 |
61 | if (selection.isEmpty) {
62 | // Without selection
63 | let currentline = selection.start.line;
64 | let currentlineText = editor.document.lineAt(currentline).text;
65 |
66 | // find the variable name in current line. To avoid any possible characters inside print(), so ignore this situation
67 | // use regex to match characters until the first occurrence of =, +=, -=, /=, //=, *=, %= and so on
68 | let regexList = currentlineText.includes("print") ? false : currentlineText.match(/.+?(?=\=|\+=|\-=|\/=|\/\/=|\*=|\%=)/);
69 |
70 | if (regexList) {
71 | // console.log("regexList[0]:" + regexList[0]);
72 | if (regexList[0].includes(',') && /^[A-Za-z0-9_,\.\s]+$/.test(regexList[0])) { // the regex is to avoid regard sth like 'm[1,2]' as unpacked variable
73 | // there are multiple unpakced variables
74 | let v_list = regexList[0].split(',');
75 | for (var variableName of v_list){
76 | // await insertCodeInNewLine(printfunction, usefstring, mode, variableName.trim(), prefix, suffix, attr, color);
77 | await vscode.commands.executeCommand('editor.action.insertLineAfter')
78 | .then(() => {
79 | const codeToInsert = getInsertCode(printfunction, usefstring, mode, variableName.trim(), prefix, suffix, attr, color);
80 | insertCode(codeToInsert);
81 | });
82 | }
83 | } else {
84 | // only single variable
85 | let variableName = regexList[0].trim();
86 | await insertCodeInNewLine(printfunction, usefstring, mode, variableName, prefix, suffix, attr, color);
87 | }
88 | } else {
89 | // Not find variable, then just insert print(), if current line is not empty, insert at next line, or just insert in current line
90 | if (currentlineText.trim()) {
91 | vscode.commands.executeCommand('editor.action.insertLineAfter')
92 | .then(() => {
93 | insertCode('print()', true);
94 | });
95 | } else {
96 | insertCode('print()', true);
97 | }
98 | }
99 | } else {// With selection
100 | const selected_text = editor.document.getText(selection).trim();
101 | const isMultipleLines = selected_text.includes('\n');
102 | // if yes, separate each line and handle each line
103 | if (isMultipleLines) {
104 | const lines = selected_text.split('\n');
105 | // get the position at the end of selection
106 | const endLine = Math.max(selection.start.line, selection.end.line);
107 | const endCharacter = editor.document.lineAt(endLine).range.end.character;
108 | const newPosition = new vscode.Position(endLine, endCharacter);
109 | // move cursor to the newPosition
110 | vscode.window.activeTextEditor.selection = new vscode.Selection(newPosition, newPosition);
111 |
112 | for (const currentlineText of lines) {
113 | // Handle each line here, similar to above `if (regexList) {...}` code block
114 | let regexList = currentlineText.includes("print") ? "" : currentlineText.match(/.+?(?=\=|\+=|\-=|\/=|\/\/=|\*=|\%=)/);
115 | let firstMatch = regexList ? regexList[0].trim() : "";
116 | if (firstMatch.includes(',') && /^[A-Za-z0-9_,\.\s]+$/.test(firstMatch)) { // the regex is to avoid regard sth like 'm[1,2]' as unpacked variable
117 | // there are multiple unpakced variables
118 | let v_list = firstMatch.split(',');
119 | for (var variableName of v_list){
120 | // await insertCodeInNewLine(printfunction, usefstring, mode, variableName.trim(), prefix, suffix, attr, color);
121 | await vscode.commands.executeCommand('editor.action.insertLineAfter')
122 | .then(() => {
123 | const codeToInsert = getInsertCode(printfunction, usefstring, mode, variableName.trim(), prefix, suffix, attr, color);
124 | insertCode(codeToInsert);
125 | });
126 | }
127 | } else if(firstMatch){// else if firstMatch is not empty which means match single variable
128 | // await insertCodeInNewLine(printfunction, usefstring, mode, firstMatch, prefix, suffix, attr, color);
129 | // above code does not work if execute multiple times in a for loop
130 | await vscode.commands.executeCommand('editor.action.insertLineAfter')
131 | .then(() => {
132 | const codeToInsert = getInsertCode(printfunction, usefstring, mode, firstMatch, prefix, suffix, attr, color);
133 | insertCode(codeToInsert);
134 | });
135 | }
136 | }
137 | } else {// Handle single line
138 | if (selected_text.includes(',') && /^[A-Za-z0-9_,\.\s]+$/.test(selected_text)){
139 | // there are multiple unpakced variables
140 | let v_list = selected_text.split(',');
141 | for (var variableName of v_list){
142 | // await insertCodeInNewLine(printfunction, usefstring, mode, variableName.trim(), prefix, suffix, attr, color);
143 | await vscode.commands.executeCommand('editor.action.insertLineAfter')
144 | .then(() => {
145 | const codeToInsert = getInsertCode(printfunction, usefstring, mode, variableName.trim(), prefix, suffix, attr, color);
146 | insertCode(codeToInsert);
147 | });
148 | }
149 | } else {
150 | const linecontent = editor.document.lineAt(selection.start.line).text.trim();
151 | // If the selected content is exactly the content of the entire line, it will treat the selected content as a variable and insert code at the current line, or insert at next line
152 | if(selected_text === linecontent) {
153 | const codeToInsert = getInsertCode(printfunction, usefstring, mode, selected_text, prefix, suffix, attr, color);
154 | editor.edit((editBuilder) => editBuilder.replace(selection, codeToInsert));
155 | } else {
156 | await insertCodeInNewLine(printfunction, usefstring, mode, selected_text, prefix, suffix, attr, color);
157 | }
158 | }
159 | }
160 | }
161 | };
162 |
163 | async function handleCommentOut(mode:string) {
164 | let editor = vscode.window.activeTextEditor;
165 | if (!editor) {
166 | vscode.window.showErrorMessage('Can\'t comment out print() because no python file is opened or cursor is not focused');
167 | return;
168 | }
169 | let start, end;
170 | let selection = editor.selection;
171 | if (selection.isEmpty) {
172 | let totalCount = editor.document.lineCount;
173 | switch (mode) {
174 | case 'all':
175 | start = 0;
176 | end = totalCount;
177 | break;
178 | case 'up':
179 | start = 0;
180 | end = editor.selection.start.line;
181 | break;
182 | case 'down':
183 | start = editor.selection.end.line;
184 | end = totalCount;
185 | break;
186 | default:
187 | start = 0;
188 | end = totalCount;
189 | break;
190 | }
191 | } else {
192 | start = editor.selection.start.line;
193 | end = editor.selection.end.line;
194 | }
195 | // toggle
196 | for (let i = start; i < end+1; i++) {
197 | let line = editor.document.lineAt(i);
198 | const lineText = line.text.trim();
199 | // comment the line
200 | if (lineText.startsWith("print(") || lineText.startsWith("prints(")) {
201 | await editor.edit(editBuilder => {
202 | // get the indent position
203 | const indent = line.firstNonWhitespaceCharacterIndex;
204 | const p = new vscode.Position(i, indent);
205 | editBuilder.insert(p, '# ');
206 | });
207 | } else if (lineText.startsWith("# print(") || lineText.startsWith("# prints(")) {
208 | // uncomment the line
209 | await editor.edit(editBuilder => {
210 | const indent = line.firstNonWhitespaceCharacterIndex;
211 | let toDeleteRange = new vscode.Range(line.range.start.translate(0,indent), line.range.start.translate(0, indent+2));
212 | editBuilder.delete(toDeleteRange);
213 | }
214 | );
215 | }
216 | }
217 | }
218 |
219 | export function activate(context: vscode.ExtensionContext) {
220 | console.log('Quick Python Print is now active!');
221 |
222 | let printfunction:string = vscode.workspace.getConfiguration().get('0.print function');
223 | let usefstring:boolean = vscode.workspace.getConfiguration().get('1.enable formatted string');
224 | let prefix:string = vscode.workspace.getConfiguration().get('2.prefix');
225 | let suffix:string = vscode.workspace.getConfiguration().get('3.suffix');
226 | let attr1:string = vscode.workspace.getConfiguration().get('4.1.attribute1');
227 | let attr2:string = vscode.workspace.getConfiguration().get('4.2.attribute2');
228 | let builtinfunc:string = vscode.workspace.getConfiguration().get('5.function');
229 | let colortext:boolean = vscode.workspace.getConfiguration().get('6.1.enable colored output text');
230 | let color1:string = vscode.workspace.getConfiguration().get('6.2.color for ctrl shift l');
231 | let color2:string = vscode.workspace.getConfiguration().get('6.3.color for ctrl shift o');
232 | let color3:string = vscode.workspace.getConfiguration().get('6.4.color for ctrl shift t');
233 | let delimierSymbol:string = vscode.workspace.getConfiguration().get('7.1.delimiter symbol for ctrl shift ;');
234 | let delimierLength:string = vscode.workspace.getConfiguration().get('7.2.delimiter length for ctrl shift ;');
235 | let delimierColor:string = vscode.workspace.getConfiguration().get('7.3.delimiter color for ctrl shift ;');
236 |
237 | // monitor the configuration changes and update them
238 | context.subscriptions.push(vscode.workspace.onDidChangeConfiguration(() => {
239 | printfunction = vscode.workspace.getConfiguration().get('0.print function');
240 | usefstring = vscode.workspace.getConfiguration().get('1.enable formatted string');
241 | prefix = vscode.workspace.getConfiguration().get('2.prefix');
242 | suffix = vscode.workspace.getConfiguration().get('3.suffix');
243 | attr1 = vscode.workspace.getConfiguration().get('4.1.attribute1');
244 | attr2 = vscode.workspace.getConfiguration().get('4.2.attribute2');
245 | builtinfunc = vscode.workspace.getConfiguration().get('5.function');
246 | colortext = vscode.workspace.getConfiguration().get('6.1.enable colored output text');
247 | color1 = vscode.workspace.getConfiguration().get('6.2.color for ctrl shift l');
248 | color2 = vscode.workspace.getConfiguration().get('6.3.color for ctrl shift o');
249 | color3 = vscode.workspace.getConfiguration().get('6.4.color for ctrl shift t');
250 | delimierSymbol = vscode.workspace.getConfiguration().get('7.1.delimiter symbol for ctrl shift ;');
251 | delimierLength = vscode.workspace.getConfiguration().get('7.2.delimiter length for ctrl shift ;');
252 | delimierColor = vscode.workspace.getConfiguration().get('7.3.delimiter color for ctrl shift ;');
253 | }));
254 |
255 | let disposable;
256 |
257 | disposable = vscode.commands.registerCommand('extension.python-print', () => {
258 | if (colortext) {
259 | handleInsertion(printfunction, usefstring, prefix, suffix, attr1, 0, color1);
260 | } else {
261 | handleInsertion(printfunction, usefstring, prefix, suffix, attr1, 0);
262 | }
263 | });
264 | context.subscriptions.push(disposable);
265 |
266 | disposable = vscode.commands.registerCommand('extension.python-print-tensor-shape', () => {
267 | if (colortext) {
268 | handleInsertion(printfunction, usefstring, prefix, suffix, attr2, 0, color2);
269 | } else {
270 | handleInsertion(printfunction, usefstring, prefix, suffix, attr2, 0);
271 | }
272 | });
273 | context.subscriptions.push(disposable);
274 |
275 | disposable = vscode.commands.registerCommand('extension.python-print-function', () => {
276 | if (colortext) {
277 | handleInsertion(printfunction, usefstring, prefix, suffix, builtinfunc, 1, color3);
278 | } else {
279 | handleInsertion(printfunction, usefstring, prefix, suffix, builtinfunc, 1);
280 | }
281 | });
282 | context.subscriptions.push(disposable);
283 |
284 | disposable = vscode.commands.registerCommand('extension.python-print-commentall', () => {
285 | handleCommentOut("all");
286 | });
287 | context.subscriptions.push(disposable);
288 |
289 | disposable = vscode.commands.registerCommand('extension.python-print-commentup', () => {
290 | handleCommentOut("up");
291 | });
292 | context.subscriptions.push(disposable);
293 |
294 | disposable = vscode.commands.registerCommand('extension.python-print-commentdown', () => {
295 | handleCommentOut("down");
296 | });
297 | context.subscriptions.push(disposable);
298 |
299 | disposable = vscode.commands.registerCommand('extension.python-print-deleteall', async () => {
300 | let editor = vscode.window.activeTextEditor;
301 | if (!editor) {
302 | vscode.window.showErrorMessage('Can\'t delete print() because no python file is opened or cursor is not focused');
303 | return;
304 | }
305 | let start, end;
306 | let selection = editor.selection;
307 | if (selection.isEmpty) {
308 | start = 0;
309 | end = editor.document.lineCount-1;
310 | } else {
311 | start = editor.selection.start.line;
312 | end = editor.selection.end.line;
313 | }
314 | // adapted from https://github.com/wakamex/Quick-Python-Print/blob/3f1bf41358cb9e4e0805b70f9feb2f143f2a4e88/src/extension.ts#L44
315 | await editor.edit(editBuilder => {
316 | for (let i = end; i >= start; i--) {
317 | if (/^(# )?(print|prints|pprint|logger\.debug|logger\.info)\(/.test(editor.document.lineAt(i).text.trim())) {
318 | editBuilder.delete(editor.document.lineAt(i).rangeIncludingLineBreak);
319 | }
320 | }
321 | });
322 |
323 | });
324 | context.subscriptions.push(disposable);
325 |
326 | disposable = vscode.commands.registerCommand('extension.python-print-delimiter', () => {
327 | let editor = vscode.window.activeTextEditor;
328 | if (!editor) {
329 | vscode.window.showErrorMessage('Can\'t insert separator because no python file is opened or cursor is not focused');
330 | return;
331 | }
332 | let selection = editor.selection;
333 | let codeToInsert = "";
334 | const v:string = "";
335 | if (colortext) {
336 | codeToInsert = getInsertCode(printfunction, usefstring, 2, v, delimierLength, v, delimierSymbol, delimierColor);
337 | } else {
338 | codeToInsert = getInsertCode(printfunction, usefstring, 2, v, delimierLength, v, delimierSymbol);
339 | }
340 | editor.edit((editBuilder) => editBuilder.insert(selection.start, codeToInsert));
341 | });
342 | context.subscriptions.push(disposable);
343 | }
344 |
--------------------------------------------------------------------------------
/src/test/runTest.ts:
--------------------------------------------------------------------------------
1 | import * as path from 'path';
2 |
3 | import { runTests } from '@vscode/test-electron';
4 |
5 | async function main() {
6 | try {
7 | // The folder containing the Extension Manifest package.json
8 | // Passed to `--extensionDevelopmentPath`
9 | const extensionDevelopmentPath = path.resolve(__dirname, '../../');
10 |
11 | // The path to test runner
12 | // Passed to --extensionTestsPath
13 | const extensionTestsPath = path.resolve(__dirname, './suite/index');
14 |
15 | // Download VS Code, unzip it and run the integration test
16 | await runTests({ extensionDevelopmentPath, extensionTestsPath });
17 | } catch (err) {
18 | console.error('Failed to run tests');
19 | process.exit(1);
20 | }
21 | }
22 |
23 | main();
24 |
--------------------------------------------------------------------------------
/src/test/suite/extension.test.ts:
--------------------------------------------------------------------------------
1 | import * as assert from 'assert';
2 |
3 | // You can import and use all API from the 'vscode' module
4 | // as well as import your extension to test it
5 | import * as vscode from 'vscode';
6 | // import * as myExtension from '../../extension';
7 |
8 | suite('Extension Test Suite', () => {
9 | vscode.window.showInformationMessage('Start all tests.');
10 |
11 | test('Sample test', () => {
12 | assert.strictEqual(-1, [1, 2, 3].indexOf(5));
13 | assert.strictEqual(-1, [1, 2, 3].indexOf(0));
14 | });
15 | });
16 |
--------------------------------------------------------------------------------
/src/test/suite/index.ts:
--------------------------------------------------------------------------------
1 | import * as path from 'path';
2 | import * as Mocha from 'mocha';
3 | import * as glob from 'glob';
4 |
5 | export function run(): Promise {
6 | // Create the mocha test
7 | const mocha = new Mocha({
8 | ui: 'tdd',
9 | color: true
10 | });
11 |
12 | const testsRoot = path.resolve(__dirname, '..');
13 |
14 | return new Promise((c, e) => {
15 | glob('**/**.test.js', { cwd: testsRoot }, (err, files) => {
16 | if (err) {
17 | return e(err);
18 | }
19 |
20 | // Add files to the test suite
21 | files.forEach(f => mocha.addFile(path.resolve(testsRoot, f)));
22 |
23 | try {
24 | // Run the mocha test
25 | mocha.run(failures => {
26 | if (failures > 0) {
27 | e(new Error(`${failures} tests failed.`));
28 | } else {
29 | c();
30 | }
31 | });
32 | } catch (err) {
33 | console.error(err);
34 | e(err);
35 | }
36 | });
37 | });
38 | }
39 |
--------------------------------------------------------------------------------
/test/.vscode/settings.json:
--------------------------------------------------------------------------------
1 | {
2 | }
--------------------------------------------------------------------------------
/test/demo-gif.py:
--------------------------------------------------------------------------------
1 | import torch
2 |
3 | a = torch.randn(2, 3)
4 |
5 | # test for line with indent
6 | if True:
7 | b = torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
8 | b.view(1, 6)
9 | c, d = 100, 999
10 | e = c+d
11 | f = c*d
--------------------------------------------------------------------------------
/test/demo.py:
--------------------------------------------------------------------------------
1 | import torch
2 | import tensorflow as tf
3 | import paddle
4 | import numpy as np
5 | from termcolor import colored
6 |
7 | # test for compatibility with different AI framework
8 | a = torch.randn(2, 3)
9 |
10 | b = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
11 | print("==>> b.shape: ", b.shape)
12 | print(colored("==>> type(b): ", "blue"), type(b))
13 | # print("==>> type(b): ", type(b))
14 | # print("==>> b.shape: ", b.shape)
15 |
16 | c = paddle.to_tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
17 | print("==>>c.shape: ", c.shape)
18 |
19 | d = np.array([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
20 | print(colored("==>> d.shape: ", "red"), d.shape)
21 | print(colored("==>> type(d): ", "blue"), type(d))
22 | print("==>>d.shape: ", d.shape)
23 |
24 | # test for line with indent
25 | if True:
26 | a += torch.tensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
27 | a.bernoulli_(0.1)
28 |
29 |
--------------------------------------------------------------------------------
/test/no_dl.py:
--------------------------------------------------------------------------------
1 | """test some features that are irrelevant to deep learning framework"""
2 | from termcolor import colored
3 | a, b = (1,2)
4 |
5 | if True:
6 | a_1, b6 ,Cc = (1,2,3)
7 | print(colored("==>> type(a_1): ", "blue"), type(a_1))
8 | print(colored("==>> type(b6): ", "blue"), type(b6))
9 | print(colored("==>> type(Cc): ", "blue"), type(Cc))
10 |
11 | dic = {'a':1, 'b':2}
12 | print(colored("==>> type(dic): ", "blue"), type(dic))
13 | dic["a"] = 3
14 |
15 | l = [[0,0], [1,1]]
16 | l[0,0]
17 |
18 |
19 |
--------------------------------------------------------------------------------
/test/test.py:
--------------------------------------------------------------------------------
1 | import torch
2 | from termcolor import colored
3 | from pprint import pprint
4 |
5 | features = []
6 | features.append(torch.randn(2, 3))
7 | features.append(torch.randn(2, 3))
8 | print(f"==>> type(features): {type(features)}")
9 | print(f"==>> features: {features}")
10 |
11 | # 测试一行里有多个= :Ctrl Shift L
12 | in_coord_ceilX = torch.cat(features, dim=1)
13 | print(f"==>> type(in_coord_ceilX): {type(in_coord_ceilX)}")
14 | print(f"==>> in_coord_ceilX: {in_coord_ceilX}")
15 |
16 | #测试mode=1
17 | a = (1,2)
18 | print(f"==>> a: {a}")
19 | print(f"==>> type(a): {type(a)}")
20 |
21 | # 测试分割线
22 | print("".center(50, "-"))
23 | print(colored("".center(50, "-"), "magenta"))
24 |
25 | #测试与loguru的兼容
26 | from loguru import logger
27 | # print = logger.debug
28 | print(f"==>> in_coord_ceilX.shape: {in_coord_ceilX.shape}")
29 | print(f"That's it, beautiful and simple logging!")
30 | print(f"If you're using Python {3.6}, prefer {'f-strings'} of course!")
31 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "module": "commonjs",
4 | "target": "ES2020",
5 | "outDir": "out",
6 | "lib": [
7 | "ES2020"
8 | ],
9 | "sourceMap": true,
10 | "rootDir": "src",
11 | "skipLibCheck": true
12 | // "strict": true /* enable all strict type-checking options */
13 | /* Additional Checks */
14 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
15 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
16 | // "noUnusedParameters": true, /* Report errors on unused parameters. */
17 | }
18 | }
19 |
--------------------------------------------------------------------------------