Overview
Here is to record some of my development process encountered some of the details and code optimization problems, I hope to share with June.
Copyright notice
Copyright belongs to the author.
Commercial reprint please contact the author for authorization, non-commercial reprint please specify the source.
Coding-naga
Published: March 17, 2016
Links: http://blog.csdn.net/lemon_tree12138/article/details/50854673
Source: CSDN
More content: Category >> thinking in Python
Directory
- Copyright notice
- Directory
- Artifice
- Python code gets command line output
- Do not use an expression as the default argument for a function
- Specifying the exception code block exception block parameters
- To change a list while traversing a list
- Print out JSON more gracefully
- Features of the __init__py
- Ref
Artifice 1. Python code gets command line output
This can be achieved through the popen, pipe in the subprocess module.
For example, with the following code, you can try to capture the text information of the console output:
fromimport"Hello, Shell."print(label)f = Popen(("python""catch_output.py"), stdout=PIPE).stdoutprint("Catch Output: {0}".format(f.readline()))
In the code above, we can print out our console output, as well as the output information obtained by capturing the output. As follows:
Hello, Shell.Catch Output: Hello, Shell.
2. Do not use expressions as default parameters for functions
One of the more important features of Python is that in Python's function, we can specify a default value for the parameter. However, this is a small trap. It can often be confusing for beginners, such as writing Python code like this:
def test_args(array=[]): array.append("Bob") return array
Normally, there is no problem with the above code, because it is true that "[Bob]" can be printed out. However, the problem is that it occurs on our repeated calls. What do you say? With the Test_args () method above, we make three repeated calls. The result of the printing is:
[‘Bob‘][‘Bob‘, ‘Bob‘][‘Bob‘, ‘Bob‘, ‘Bob‘]
wtf!
How is that going to work? Because the setting of the optional parameter default value is only executed once in Python .
How to understand? It's very simple, that is, our parameter default value is considered to be assigned to the default value only if the function is defined and the value of this parameter is not passed when the function is called.
It is also easy to modify this function with the following code:
def test_args(array=None): ifisNone: array = [] array.append("Bob") return array
3. Specifying the parameters of the exception code block (Exception block)
In python2.x, we know that we can use commas to specify the exception parameters. As follows:
def fun(): try: print("Hello, Exception") except Exception, e: print(e) pass
But in python3.x, there is a grammatical error in this notation. For python2.x and python3.x, however, you can use as to specify. As follows:
def fun(): try: print("Hello, Exception") exceptas e: print(e) pass
Therefore, it is better to use as to specify parameters for projects that may have version differences.
4. Change the list when traversing the list
Under normal circumstances, it is difficult for us to modify the list in the process of traversing the list, which is not only applicable in Python, but also has the same rules in Java. For example, the following syntax throws some exceptions.
def test_list_modify(): a = [012345678] lambda2) forin xrange(len(a)): if odd(a[i]): a.remove(i) print(a)
The above code is bound to throw an exception, and the exception is as follows:
last): "E:/workspace/src/Python/Demo/SimpleDemo-python/test/test_demo.py"line106in <module> test_list_modify() "E:/workspace/src/Python/Demo/SimpleDemo-python/test/test_demo.py"line76in test_list_modify if odd(aof range
The reason is also very easy to find, in the above code, we try to modify the length of the list, which causes the loop to go through the process of accessing the array under bidding clubs beyond the modified list length. To throw the above exception information.
However, we can take advantage of the elegant programming paradigm of the Python language itself. The modified code is as follows:
def test_list_modify(): a = [012345678] lambda2) forinifnot odd(n)] print(a)
5. Print out JSON more gracefully
In Python, the JSON module provides us with a very good print interface for JSON objects--json.dumps ()
Of course Json.dumps () is the JSON object, not the original JSON string. To achieve an elegant print of the original JSON string, we can encapsulate it two times.
- Converts a JSON string into a JSON object by Json.loads () ;
- Gracefully print the JSON string through json.dumps () .
ImportJsonjson_data ="{\" status\ ": \" Ok\ ", \" count\ ": 2, \" Results\ ": [{\" age\ ":" \ "" name\ ": \" oz\ ", \" lactose_intolerant\ ": true}," "{\" age\ ":", \ "name\": \ "joe\", \ "lactose_intolerant\": false}]} " def parser():Json_obj = Json.loads (Json_data) show (Json_obj)Pass def show(json_obj):Print (Json.dumps (json_obj, indent=4))Passif__name__ = =' __main__ ': Parser ()Pass
The results are printed as follows:
6. Function of __init__.py
Sometimes we need to import the contents of many other modules into a custom module, which makes the code look bloated. However, fortunately we can solve this problem by __init__.py this file. This is done by placing the code for the import module in the __init__.py file, and then importing the entire contents of the __init__.py module into the target file.
The following code is in the __init__.py:
import osimport timeimportas date
The calling code in the test file is as follows:
fromimport *print(time.ctime())print(date.date.day)print(os.system("python test_init.py"))
Of course, you can also choose to import one by one, as follows:
fromimport sysfromimport getoptfromimport packfromimport pehelpfromimport PEParserfromimport Signature
Ref
http://codingpy.com/article/top-10-mistakes-that-python-programmers-make/
http://www.vaikan.com/improving-your-python-productivity/
Python code optimization and tips notes (ii)