Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to debug code using PySnooper

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "how to debug code with PySnooper". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

1. Quick installation

Execute the following commands to install PySnooper

$python3-m pip install pysnooper # or $conda install-c conda-forge pysnooper # or $yay-S python-pysnooper

two。 Simple case

The following code defines a function of demo_func, generates a dictionary variable of profile, then updates it, and finally returns.

The code itself doesn't make much sense, but it's enough to demonstrate PySnooper.

Import pysnooper @ pysnooper.snoop () def demo_func (): profile = {} profile ["name"] = "Mingo" profile ["age"] = 27 profile ["gender"] = "male" return profile def main (): profile = demo_func () main ()

Now I use the terminal command line to run it

[root@iswbm ~] # python3 demo.py Source path:... Demo.py 17 def demo_func 52 line 49.624943 call 4 def demo_func (): 17 def demo_func 52Switzerland 49.625124 line 5 profile = {} New var:. Profile = {} 17profile 52Switzerland 49.625156 line 6 profile ["name"] = "Ming GE who wrote the code" Modified var:.. Profile = {'name':' who wrote the code'} 17 line 52 line 49.625207 line 7 profile ["age"] = 27 Modified var:.. Profile = {'name':' writing code Ming', 'age': 27} 1752age': 49.625254 line 8 profile ["gender"] = "male" Modified var:.. Profile = {'name':' coding Mingo', 'age': 27,' gender': 'male'} 17 gender': 52age': 49.625306 line 10 return profile 172age': 49.625344 return 10 return profile Return value:.. {'name':' code writer Mingo', 'age': 27,' gender': 'male'} Elapsed time: 00.000486 00.000486

You can see that PySnooper records the entire process of running the function, including:

Information such as snippets, line numbers, and so on, and when was each line of code called?

How does the value of a local variable in a function change? When variables are added and when variables are modified.

What is the return value of the function?

How long does it take to run the function?

As a developer, to get such detailed debugging information, all you need to do is put a hat (decorator) on the function you want to debug-@ pysnooper.snoop ().

3. Detailed use

2.1 Redirect to log file

When @ pysnooper.snoop () takes no parameters, it outputs debug information to standard output by default.

For BUG that can be solved with a single debug, there is no problem, but there are some BUG that appear only in specific scenarios and require you to put the program behind for a while before it can be reproduced.

In this case, you can redirect the debug information to a log file to facilitate traceability.

Pysnooper.snoop (output='/var/log/debug.log') def demo_func ():...

2.2 tracking the value of non-local variables

PySnooper is debugged on a function-by-function basis. By default, it only tracks local variables in the function. If you want to track global variables, you can add the watch parameter to pysnooper.snoop ().

Out = {"foo": "bar"} @ pysnooper.snoop (watch= ('out ["foo"]') def demo_func ():.

In this way, PySnooper will print out the out ["foo"] value when it changes

The watch parameter, which receives an iterable object (which can be list or tuple), and the elements in it are string expressions. What does that mean? Just look at the following example.

Pysnooper.snoop (watch= ('out ["foo"]', 'foo.bar',' self.foo ["bar"]') def demo_func ():.

In contrast to watch, pysnooper.snoop () can also receive a function called watch_explode, which means that all global variables except these parameters are monitored.

Pysnooper.snoop (watch_explode= ('foo',' bar')) def demo_func ():...

2.3 set the depth of the trace function

When you use PySnooper to debug a function, if other functions are called in that function, PySnooper will not foolishly trace it in.

If you want to continue tracking other functions called in this function, you can set the trace depth by specifying the depth parameter (if not specified, the default is 1).

Pysnooper.snoop (depth=2) def demo_func ():...

2.4 set the prefix for debug logs

When you are using PySnooper to track multiple functions, the debug log will appear disorganized and inconvenient to view.

In this case, PySnooper provides a parameter that makes it easy for you to set different flags for different functions and to distinguish them when viewing logs.

Pysnooper.snoop (output= "/ var/log/debug.log", prefix= "demo_func:") def demo_func ():...

The effect is as follows

2.5 set the maximum output length

By default, the variable and exception information output by PySnooper will be truncated to 100 characters if it exceeds 100 characters.

Of course, you can also modify it by specifying parameters.

Pysnooper.snoop (max_variable_length=200) def demo_func ():...

You can also use max_variable_length=None, which never truncates them.

Pysnooper.snoop (max_variable_length=None) def demo_func ():...

2.6 support for multithreaded debugging mode

PySnooper also supports multithreaded debugging, and by setting the parameter thread_info=True, it prints in the log in which thread the variable was modified.

Pysnooper.snoop (thread_info=True) def demo_func ():...

The effect is as follows

2.7 format output of custom objects

The pysnooper.snoop () function takes an argument to custom_repr, which takes a tuple object.

In this tuple, you can specify that specific types of objects are output in a specific format.

Let me give you an example here.

If I want to track person, an object of type Person, because it is not a regular Python base type, PySnooper cannot properly output its information.

So I set the custom_repr parameter in the pysnooper.snoop () function, the first element of which is Person and the second element is the print_persion_obj function.

When PySnooper prints the debug information of an object, it determines whether it is an object of type Person one by one. If so, it passes the object into the print_persion_obj function, which decides how to display the information of the object.

Class Person:pass def print_person_obj (obj): return f "" @ pysnooper.snoop (custom_repr= (Person, print_person_obj)) def demo_func ():...

The complete code is as follows

Import pysnooper class Person:pass def print_person_obj (obj): return f "" @ pysnooper.snoop (custom_repr= (Person, print_person_obj)) def demo_func (): person = Person () person.name = "Code writer" person.age = 27 person.gender = "male" return person def main (): profile = demo_func () main ()

Run it and observe the effect.

If there are many types of output in your custom format, the value of the custom_repr parameter can be written as follows

Pysnooper.snoop (custom_repr= ((Person, print_person_obj), (numpy.ndarray, print_ndarray)) def demo_func ():.

I would also like to remind you that the first element of a tuple can be a type (such as the class name Person or other underlying type list, etc.), or a function that determines the type of object.

In other words, the following three ways of writing are equivalent.

# [first way] @ pysnooper.snoop (custom_repr= (Person, print_persion_obj)) def demo_func ():. # [second way] def is_persion_obj (obj): return isinstance (obj, Person) @ pysnooper.snoop (custom_repr= (is_persion_obj) Print_persion_obj)) def demo_func ():... # [the third way to write] @ pysnooper.snoop (custom_repr= (lambda obj: isinstance (obj, Person), print_persion_obj)) def demo_func ():... " This is the end of how to use PySnooper to debug code. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report