Abstract:Python is a cross-platform programming language that can run any Python program you write on all major operating systems. Today we’ll cover a few common tools: Python’s native interpreter, Text editors (Geany, Sublime Text), mainstream ides (PyCharm, Jupyter Notebook), and how to use the computing resources of the public cloud to develop locally.
preface
Python is getting more attention than usual this year, becoming one of the most popular programming languages in the world.
— by Krzyszt
For technical articles, I tend to think of lofty descriptions or human stories. However, for a universal programming language like Python, I think the above colloquial description from Krzyszt is sufficient.
Python is a cross-platform programming language, which means it can run any Python program you write on any major operating system. In today’s article, we’ll look at some common tools, including Python’s native interpreter, Text editors (Geany, Sublime Text), mainstream ides (PyCharm, Jupyter Notebook), and how to use public cloud computing resources for local development.
The body of the
Python’s native interpreter
Python comes with an interpreter that runs in a terminal window. You don’t need to save the code. You can run the entire program directly, as shown below:
Geany
Geany is a simple text editor that is easy to install, allows you to run almost any program directly (you don’t need to run it from a terminal), uses color to distinguish key code, and highlights code syntax.
You can download Geany at geany.org/.
Once the installation is complete, first create a local folder to hold and run the code, such as the python_work folder.
Create a new file and SAVE it to the Pytthon_word folder by “SAVE AS”.
If you have Python installed, that is, if you can run python on your system, you do not need to configure Geany. If you cannot run Python successfully, you need to configure Geany.
The code involved and the code to run is the “Build” button, as shown below:
Start by executing a helloWolrld command, as shown below:
To further explain the functions listed in the Generate drop-down box, I use the Armstrong number, which means that an n-bit positive integer is called an Armstrong number if it is equal to the sum of the NTH powers of its digits. For example, 1^3 + 5^3 + 3^3 = 153.
The code is as follows:
# take input from the user
num = int(input("Enter a number: "))
# initialize sum
sum = 0
# find the sum of the cube of each digit
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
# display the result
if num == sum:
print(num,"is an Armstrong number")
else:
print(num,"is not an Armstrong number")Copy the code
“Compile” : Compiles code, similar to python -m py_compile helloworld.py, to generate a. Pyc file. Pyc is a binary file that is generated by compiling the py file and belongs to Byte code. Pyc is a cross-platform bytecode that is executed by the Python virtual machine, which is similar to JAVA or PyC. NET virtual machine concept. The content of pyC varies with the Python version. Pyc files compiled for different versions are different. For example, PYC files compiled for V2.5 cannot be executed on Python version 2.4.
“Lint” : this will statically check code for tab-characters, Spaces, variable names, etc. In this case, only 3 Spaces are indented in the middle line, and “num,” on line 18 will not have a space, as follows:
After the code is modified, it will show normal compilation, as shown below:
“Generate target file” : Run the “make current_file.o” file, with the benefit that only the currently specified file is compiled, not the entire project.
“Execute” : the terminal compiler that actually calls Python, as shown below:
Geany’s interface and compiler support personalization. Instead of going through it one by one, you can try it yourself by going through “Edit” – “Preferences”.
Sublime Text
Like Geany, Sublime Text is a simple Text editor that runs almost any program directly (without the need for a terminal), supports different colors for key code, and highlights code syntax.
Sublime Text benefits:
- Cross-platform: Sublime Text is a cross-platform editor (available on Linux, OS X, and Windows). As a programmer, switching between systems is a common thing, and it is necessary to use a cross-platform editor in order to reduce repetitive learning.
- Extensible: Sublime Text is Extensible and includes a lot of utility plugins, so we can exponentially increase productivity by installing plugins for our own domain;
- Complementary: Sublime Text is the best choice for both command line (CLI) and graphical interface (GUI) environments, and using both greatly improves productivity.
Sublime Text is really a programmer’s tool from a usage point of view. For example, all Settings are done through JSON configuration files and it feels good to write your own configuration files.
As shown in the image above, I set the font size in the programmable bar on the right, and as soon as I save this document, Sublime Text’s already open window executes immediately.
Sublime Text supports simultaneous selection of multiple areas and then simultaneous editing. Ctrl + D selects the word where the cursor is and highlights all occurrences of the word. Ctrl + D again selects the next occurrence of the word. In the process of multiple word selection, press Ctrl + K to skip, Ctrl + U to roll back, and Esc to exit multiple editing. This is great, the people who write the code feel much more productive!
PyCharm
PyCharm is an integrated development environment (IDE) for computer programming, primarily for Python. Developed by Czech company JetBrains, PyCharm provides code analysis, graphical debugger, integration tester, integrated version control system, and web development using Django. PyCharm is a cross-platform development environment available in Microsoft Windows, macOS, and Linux versions. The Community edition is released under the Apache license, and the Professional edition is released under a proprietary license with many additional features.
PyCharm is very powerful and contains almost every feature you can think of yourself. I think the key to judging the viability of an IDE is to support code refactoring and leverage surrounding ecosystems (such as public cloud computing resources), so I’ll focus on those two features here.
Let’s start with code refactoring. Refactoring refers to the use of a series of refactoring techniques to adjust the structure of software without changing its observable behavior. We usually speak code refactoring, yes there are the most common categories, such as duplicate code (more than one site to see the same program structure) and long (generally no more than 500 rows) and the parameters of the long column (too long parameters are difficult to understand, too many parameters can lead to inconsistent, not easy to use, and if you need more data, You have to modify it), divergent variations (if a class is constantly changing in different directions for different reasons, then it might be better to split the object into two so that each object can be modified for just one change), redundant classes, and so on.
Let’s look at a specific case:
Constants and temporary variables
Suppose you have a literal value with special meaning, as shown in the following code. Create a constant, name it according to its meaning, and replace the literal value above with this constant.
def potential_energy(mass, height):
returnMass * 9.81 * heightCopy the code
Here, the 9.81 would be GRAVITATIONAL_CONSTANT
Choose Constant:
Change the code to something like this:
2. Simplify complex expressions, such as the following code:
if "MAC" in platform.upper() and "IE" in browser.upper() and was_initialized() and resize > 0:
#do somethingCopy the code
We can change “MAC” in platform.upper() to a variable, meaning that the variable name is used to explain the expression’s purpose.
The code is refactored as shown below:
3. Abstract out reusable methods and reduce the amount of code for business methods. Here is an example code for the greatest common divisor
The original code is as follows:
Now to extract the greatest common divisor into a separate method, select lines 10-14 from the above image and click the ‘Refactor’ button.
The code was refactored to:
The variable factor gets rid of variables by using Inline variable refactoring. We select the variable Factor and press Ctrl+Alt+N. All detected Factor variables are inline.
Use Change Signature to Change the parameter name. Select the method declaration line, then press Ctrl+F6. In the dialog box that opens, rename the parameters denom and num to X and Y, respectively, and then click the icon node upLevel to change the order of the parameters.
Can PyCharm do better than native IDE tools? I think PyCharm’s development has become normal. I think what we should do now is to expand, or unite, the ecology. With whom? And public cloud. If you can code locally and debug using the computing resources of the public cloud, it is equivalent to achieving cloud side collaboration. Huawei cloud ModelArts provides a plug-in, support local PyCharm together with ModelArts use (please refer to the detailed process document: bbs.huaweicloud.com/blogs/16046…). .
We really only need to do three steps to support native PyCharm in conjunction with the ModelArts platform:
1. Download and install the plug-in;
2. Apply for the secret key of ModelArts website;
3. PyCharm Enter key value pairs.
If you think of PyCharm as the Client side of C/S design mode and ModelArts as the Server side, it’s easy to understand.
Here I give a practical use case – handwriting model training case.
First, download the hand writing data sets: modelarts-cnnorth1-market-dataset.obs.cn-north-1.myhuaweicloud.com/dataset-mar…
Log in to huawei cloud and upload OBS.
Create two folders, one for the dataset and one for the logs generated by the training (need to be passed back to PyCharm IDE and displayed) :
To fill in the parameters, refer to the parameters filled in ModelArts training model:
Then open the project in PyCharm and click “Run Training Job” :
In the log output above, the lower left corner is the local output, and the lower right corner is the cloud training log returned by ModelArts.
After the training, the training model is saved in OBS/project name /output/V0006/.
Jupyter Notebook
Jupyter, as a special presence in AI research and exploration scenarios, has quickly grown to be the first choice for AI exploration scenarios, able to satisfy developers’ needs at all stages and cover these key points, as well as supporting features for use in browsers.
Jupyter began as a Project called IPython, which started as a Python-focused project but has grown beyond the Python programming language. According to the founders of Jupyter, the original goal of Jupyter was to create an interactive computing platform that supports Julia (Ju), Python (Py) and R, so it was named Ju-py-te-R. Jupyter has since grown to support almost all languages. It is a multi-functional scientific computing platform that can integrate codes, computational output, interpretation documents and multimedia resources.
Another concept that needs to be mentioned here is “literary programming”, a programming paradigm developed by Donald Knuth. This paradigm provides the opportunity to interpret program logic in natural language. In short, the readers of literary programming are not machines, but people. We went from writing code that machines could read to explaining to people how machines could implement our ideas, with more narrative text, diagrams, and so on than code. Literary programming is interspersed with macro fragments and traditional source code from which compilable source code can be generated.
As the first life-cycle tool platform for scientific computing, Notebook can be divided into individual exploration, collaboration and sharing, production operating environments, publishing and teaching.
Are there any drawbacks to Jupyter? There is. If you are looking for production-oriented code development, such as code formatting, dependency management, product packaging, unit testing, etc., are not well supported in ides. There are plug-ins available, but they are still weak compared to heavy-duty ides. In addition, Jupyter is defined as a debugging environment for research. On the one hand, distributed tasks are currently recommended to be simulated by single-machine multi-process, and real parts with multi-node topology information are not easy to achieve in Jupyter. On the other hand, the architecture of Jupyter is not suitable for very heavy tasks. For real software product development, it is still necessary to do the engineering code development in the IDE, and with the test logic, the task is deployed in a cluster to run.
Let’s see how Jupyter works, right? First create a Notebook on the public cloud and click the “Open” button, as shown below:
The selection is based on which computing engine (e.g. Tensorflow-1.8), as shown below:
Output code snippet. In the first code, since user input has been requested, we need to input a number. As long as it is a normal integer number, no error will be reported, as shown below:
Afterword.
The postscript to this article is hard to write because tools are always evolving and it’s hard to predict where a particular tool will go in the future, but the rule of thumb is that tools must serve developers, and they must become simpler.
Editors and ides are fundamentally tools for two different usage scenarios:
- The editor is for plain text without semantics and does not involve domain logic, so it is fast and small, suitable for writing individual configuration files and dynamic language scripts (Shell, Python, Ruby, etc.).
- IDE is oriented towards semantic code, which involves a lot of domain logic, so it is slow and bulky, suitable for writing static language projects (Java, C++, C#, etc.).
Personally, I think we should use the right tools to do valuable things and maximize efficiency, so I write Java projects with IntelliJ IDEA, Shell with Vim, JavaScript/HTML/Python with Sublime Text, Write C# in Visual Studio.
At The end of this article, I’ll refer to The Zen of Python (typing import this in The Python interactive interpreter will display Tim Peters’ The Zen of Python) :
>>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Spacing is better than compactness (keep spacing properly and don't expect a single line of code to solve the problem) Readability is important (to keep your code readable and constantly improve it)'t special enough to break the rules. What was once a matter of practicality is better than purity. Errors should never pass silently. Errors must not be explicitly silenced. Unless it is explicitly required to do so. In the face of uncertainty, we should be one-- and preferably only one-- obvious way to do it. Although that way may not be obvious at first unless you'Although this may not be so intuitive at first, unless you're A Dutchman. Although never is often better than *right* now. However, it is better not to do If the implementation is hard to explain, itIf the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's domore of those! Advocate the use of namespacesCopy the code
These preparations apply not only to Python, but to all programming languages.
Click to follow, the first time to learn about Huawei cloud fresh technology ~