Programmer's Swiss Army knife----Python

Source: Internet
Author: User
Tags glob ruby on rails

This article is more difficult to shape. Presumably, the programmer should be able to do some "batch" or "automated" operations through a scripting language rather than repeating manual work.

Specific ways, such as someone very familiar with bat or shell writing, or someone is very familiar with PHP, Perl writing, and I contacted Python earlier, so many tools more accustomed to use Python to complete.

Here's a look at my various requirements and scripting language choices, followed by a lot of "idioms" for Python that will keep track of the features and snippets you use.


First, the summary

Python is a fairly sophisticated scripting language that can handle virtually every need in the real world. Of course I am not a backend programmer and will not use it to develop server functionality. But as a "Swiss Army knife", even though I only use Python's simple features, it also provides a lot of convenience for my work.

1, batch file renaming, very simple six or seven lines of code can be done, and more free, more powerful than the tools on the Web. For example, you can find or match regular matches to provide more complex replacement options.

2, batch execution of an operation, such as texture Packer bulk packaging, Batch conversion resources, batch DDS to PNG, batch model conversion, batch LUA file encryption and so on. This is done by executing a system command on Os.system. Python provides more flexible functionality, such as you can use the process without using Os.system, although the code is more complex, but you can listen to the execution of the command. You can generate a corresponding configuration at the same time as the file is converted. You can also automatically create a corresponding directory structure.

3, picture processing. PIL (Python Image Library, need to download separately, is a third-party library, Python's third-party library of a wide variety, almost no can not be implemented) can do some column operation for the picture, very simple, a few lines of code can be done, such as to expand the image to 2 of the power of the whole, Large picture cut into small pictures, pictures stretching or shrinking, etc., can also not rely on texture packer and image format conversion.

4, text operation. Python's regular expressions are powerful and can be easily matched and captured to complete some text manipulation. For example, each header file is inserted at the beginning of the copyright notice. Change the. png in a plist to. PVR.CCZ, etc.

5, Excel operation. This is actually a text operation, but because of the need to download third-party libraries (XLRD), and the function is also very important, so separate mention. Python can read and write content in Excel, generating configuration formats that are required by the client or server, such as JSON, XML, CSV, and so on. More clear and convenient, there is really no need to engage in any VB script.

6, automatic function. This is basically an extended version of the bulk execution operation. With Python, you can automate some column operations, eliminating manual errors and increasing productivity. For example, automatically compare the differences between two folders, copy the diff file, generate a ZIP package, and update the configuration table.

Basically programmers prefer the way the command line, not the program may be more inclined to GUI, Python also support PYQT to develop GUI programs, you can also use the tool to package the script as EXE to publish, so the target machine does not need to rely on the Python library.

Based on the requirements above, Python (Perl has not learned, but I personally still quite good) is the most satisfying condition. Some of the other languages, though, have some advantages, but obviously they have more expertise. Like what:

1, bat and Shell, this is based on the operating system batch processing, bat function is weak, and not as good as Python syntax clean, want to write to some of the more complex bat statement is not easy. The shell is basically not able to run under Windows unless Cygwin is installed.

2, PHP. The first quick-cocos2dx is to take PHP as a scripting language to do some text processing operations. However, PHP environment is very difficult to build, need Apache, MySQL a lot of things, it is obvious that it should be obediently when the server back end, rather than the "Swiss Army Knife"

3, Ruby. This is really not a contact, but if there is no Ruby on Rails,ruby will not develop. Do the website with the same peace of mind.

4, Lua. The client is very common, the syntax is very familiar, but unfortunately there are few third-party libraries, a lot of things need to use C + + to implement it again, and then exported to Lua. This is obviously a problem. And there is an interesting thing is that, before someone took Lua and C + + implementation of Excel exported to LUA program, the export time of nearly 10 seconds, and I re-implemented with Python, the export time of less than 1 seconds. It is visible that LUA is only suitable for glue language. Lua is a blade, with a sharp edge to the place, with the wrong easy to draw their own hands.

5, node. js. This is also a choice for a handyman, but its third-party library is more for the backend. And because of its asynchronous requirements, the code to read and write the file will be very disgusting, and my most commonly used is this feature.

6, Golang, D language. Golang Grammar is very strange, I do not want to see two eyes to learn, D language has not developed, these two are compiled level, not the scripting language

7, C, C + +, C #, Java. These languages are omnipotent, but they are slightly more complicated than scripting languages. This complexity is not reflected in the grammatical level, but the operation cost. For example, I write a Python script 6 lines of code, instant fix. But C + + to compile, to publish, to pay attention to a variety of dependencies, to focus on engineering configuration and so on.

Second, customary law

1. Solution unicodeencodeerror: ' ASCII ' codec can ' t encode characters in position

Python's most troubling is the character set processing, because it is a scripting language, so the problem of character sets is not only reflected in the input and output, the script itself to specify the character set, the problem of character set in the run will also cause an exception (not just the output text error)

Character set problem, add two sentences before the file:

Reload (SYS) sys.setdefaultencoding ("Utf-8")

2. JSON output Chinese exception

The Python Json.dumps method is exported to this format by default as "\u535a\u5ba2\u56ed".
To output Chinese you need to specify the ENSURE_ASCII parameter to False, the following code fragment

Json.dumps ({' Text ': "Chinese"},ensure_ascii=false,indent=2)

3, String connection

', '. Join (values)
Values is an array of strings, which means that each string in values is concatenated by commas. A word can be done, do not need to traverse their own stitching and focus on whether the last comma to add and so on.


4. Type Determination

You can determine the type of a variable by using the type directly, such as

Type (' 123 ') = = Unicodetype (123) = = int

There are some additional processing situations in the application, such as the determination of floating-point type and integral type

Type (eval ("123")) = = Inttype (eval ("123.23")) = = Float
If the above does not satisfy the demand, there is a way to trickery a little

int (number) = = Number  #整数

5. Text traversal

fp = open (' filename ', ' r ') for line in FP:    xxxxx

6. Filter files

FileList = Glob.glob (Source_path + "/*.xls*");

7. File traversal

For root, dirs, files in Os.walk (Source_path): For each in Files:file = Os.path.join (root, each);


8. Get the file name

filename = os.path.basename (file);

9. Execute exe

Os.system (' command content ')
Execute script finish Press any key to exit

Os.system (' PAUSE ');

10. Determine if files and folders exist

Os.path.exists (Cfgfile)

11. Create folders (automatically created by directory structure)

If not os.path.exists (OutputPath): Os.makedirs (OutputPath);

12. Get the current directory

OS.GETCWD ()

To be Continued ...




Programmer's Swiss Army knife----Python

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.