async def send_data(self, content, mutation=None, action=None, namespace=None): """ 为VueNativeWebSocket添加namespace等并发送 指定action或者mutation其中一个 :param dict or list content: :param str mutation: :param str action: :param str namespace: :return: """ with pysnooper.snoop(): namespace = self.namespace if namespace is None else namespace send_data = {'namespace': namespace} if mutation and action: raise ConsumerException('mutation and action is only one.') if (not mutation) and (not action): raise ConsumerException('mutation or action must be set.') if mutation: send_data['mutation'] = mutation if action: send_data['action'] = action if not isinstance(content, dict): content = { 'data': content, } content.update(send_data) await self.send_json(content)
def avg(args): # return sum(args) / len(args) sum_num = sum(args) # 分析片段代码 with pysnooper.snoop(): avg_num = sum_num / len(args) return avg_num
def division(start, end): for i in range(start, end, -1): with pysnooper.snoop(): num1 = i num2 = i - 1 result = num1 / num2 print(result)
def test_rejecting_async_generator_functions(): if sys.version_info[:2] <= (3, 6): pytest.skip() code = textwrap.dedent(''' async def foo(x): yield 'lol' ''') namespace = {} exec(code, namespace) foo = namespace['foo'] assert not pycompat.iscoroutinefunction(foo) assert pycompat.isasyncgenfunction(foo) with pytest.raises(NotImplementedError): pysnooper.snoop()(foo)
def test_statement(): with pysnooper.snoop(prefix='Statement '): a1 = 1 a2 = np.array([13, 3, 3, 4, 4, 6]) a2 = a2.reshape(2, -1) a3 = 1 a3 = a2
def sum2(x, y): for i in range(0, 50, 1): z = x + y + i print(z) with pysnooper.snoop(): sum_xy = x + y count = i print(sum_xy, count)
def register_pysnooper_tracer(app: Flask): if app.config.get('PYSNOOPER_TRACE'): try: import pysnooper for func_name, func in app.view_functions.items(): app.view_functions[func_name] = pysnooper.snoop(depth=2)(func) except ImportError: pass
def __snoop(*args, **kwargs): if os_name != 'nt' and do_not_effect_on_linux: # 不要修改任何代码,自动就会不在linux上debug,一般linux是部署机器。 return func(*args, **kwargs) else: if line_can_click: return _snoop_can_click(output, variables, depth, prefix)(func)(*args, **kwargs) else: return pysnooper.snoop(output, variables, depth, prefix)(func)(*args, **kwargs)
def number_to_bits(number): if number: bits = [] while number: number, remainder = divmod(number, 2) with pysnooper.snoop(): bits.insert(0, remainder) return bits else: return [0]
def foo(): lst = [] for i in range(10): lst.append(random.randrange(1, 1000)) with pysnooper.snoop(): lower = min(lst) upper = max(lst) mid = (lower + upper) / 2 print(lower, mid, upper)
def test_lambda(): string_io = io.StringIO() my_function = pysnooper.snoop(string_io)(lambda x: x**2) result = my_function(7) assert result == 49 output = string_io.getvalue() assert_output(output, ( VariableEntry('x', '7'), CallEntry(source_regex='^my_function = pysnooper.*'), LineEntry(source_regex='^my_function = pysnooper.*'), ReturnEntry(source_regex='^my_function = pysnooper.*'), ))
def func_p(x): ''' ''' y = x + x with pysnooper.snoop(): if y > 10: y += 10 else: y += 20 return y
def test_disable(): string_io = io.StringIO() def my_function(foo): x = 7 y = 8 return x + y with mini_toolbox.TempValueSetter((pysnooper.tracer, 'DISABLED'), True): with pysnooper.snoop(string_io): result = my_function('baba') output = string_io.getvalue() assert not output
def inner(cls: Type[T]) -> Type[T]: methods = inspect.getmembers(cls, predicate=inspect.isfunction) for name, method in methods: snooper_method = pysnooper.snoop( output, watch, watch_explode, depth, prefix, overwrite, thread_info, custom_repr, max_variable_length, )(method) setattr(cls, name, snooper_method) return cls
def test_activate_deactivate_snoop(): string_io = io.StringIO() def my_function(foo): x = 7 y = 8 return x + y pysnooper.tracer.DISABLED = '1' with pysnooper.snoop(string_io): result = my_function('baba') output = string_io.getvalue() assert output == "" pysnooper.tracer.DISABLED = '' test_string_io()
def test_lambda(normalize): string_io = io.StringIO() my_function = pysnooper.snoop(string_io, normalize=normalize)(lambda x: x ** 2) result = my_function(7) assert result == 49 output = string_io.getvalue() assert_output( output, ( SourcePathEntry(), VariableEntry('x', '7'), CallEntry(source_regex='^my_function = pysnooper.*'), LineEntry(source_regex='^my_function = pysnooper.*'), ReturnEntry(source_regex='^my_function = pysnooper.*'), ReturnValueEntry('49'), ), normalize=normalize, )
def test_var_order(normalize): string_io = io.StringIO() def f(one, two, three, four): five = None six = None seven = None five, six, seven = 5, 6, 7 with pysnooper.snoop(string_io, depth=2, normalize=normalize): result = f(1, 2, 3, 4) output = string_io.getvalue() assert_output( output, ( SourcePathEntry(), VariableEntry(), VariableEntry(), VariableEntry(), LineEntry('result = f(1, 2, 3, 4)'), VariableEntry("one", "1"), VariableEntry("two", "2"), VariableEntry("three", "3"), VariableEntry("four", "4"), CallEntry('def f(one, two, three, four):'), LineEntry(), VariableEntry("five"), LineEntry(), VariableEntry("six"), LineEntry(), VariableEntry("seven"), LineEntry(), VariableEntry("five", "5"), VariableEntry("six", "6"), VariableEntry("seven", "7"), ReturnEntry(), ReturnValueEntry(), ), normalize=normalize, )
def test(): testit = LargeAndSmall(LargeAndSmall.testData()) with pysnooper.snoop(watch=['tmp']): tmp = testit.getLarge(3, 'price') tmp = testit.getSmall(3, 'price')
def f1(x1): str(3) with pysnooper.snoop(string_io, depth=3, normalize=normalize): result1 = f2(x1) return result1
import pysnooper as ps """ scrap ptt index basic usage """ import requests as req with ps.snoop('log.txt'): h = dict(cookie='over18=1;') res = req.get("https://www.ptt.cc/bbs/Gamesale/index4030.html", headers=h) res.raise_for_status() # with open("t.html" ,"wb") as f: print(res.content.decode("utf-8")) # f.write( res.content) """ 使用scrapy 開啟 "https://www.ptt.cc/bbs/Gamesale/index.html" 步驟: $: scrapy shell from scrapy import Request url = "https://www.ptt.cc/bbs/Gamesale/index.html" req=Request(url, cookies={'over18':'1'} ) fetch(req) r = response """ #接下來 可對r進行一系列操作 """ 對response操作: x = r.css("div.title") x2 = x.css("a::text") # 取資料
import pysnooper with pysnooper.snoop(depth=2, output='log\py_variable.log'): # coding=utf-8 while True: a, b = input().split() k = 1 if len(a) != len(b): print("No") k = 0 elif len(a) == len(b) == 0: print("Yes") k = 0 if k == 1: List = [] List.append(a) for i in range(1, len(a) - 1): List.append(a[i] + a[i + 1:] + a[:i]) List.append(a[-1] + a[:len(a) - 1]) if b in List: print("Yes") else: print("No")
import torch import pysnooper def large(l): return isinstance(l, list) and len(l) > 5 def print_list_size(l): return 'list(size={})'.format(len(l)) def print_ndarray(a): return 'ndarray(shape={}, dtype={})'.format(a.shape, a.dtype) def print_tensor(tensor): return 'torch.Tensor(shape={}, dtype={}, device={})'.format( tensor.shape, tensor.dtype, tensor.device) custom_repr = ((large, print_list_size), (np.ndarray, print_ndarray), (torch.Tensor, print_tensor)) snooper_config = { 'custom_repr': custom_repr, } my_snooper = pysnooper.snoop('debug.log', **snooper_config)
def f1(x1): str(3) with pysnooper.snoop(string_io, depth=3): result1 = f2(x1) return result1
def test_with_block(): # Testing that a single Tracer can handle many mixed uses snoop = pysnooper.snoop() def foo(x): if x == 0: bar1(x) qux() return with snoop: # There should be line entries for these three lines, # no line entries for anything else in this function, # but calls to all bar functions should be traced foo(x - 1) bar2(x) qux() int(4) bar3(9) return x @snoop def bar1(_x): qux() @snoop def bar2(_x): qux() @snoop def bar3(_x): qux() def qux(): return 9 # not traced, mustn't show up with mini_toolbox.OutputCapturer(stdout=False, stderr=True) as output_capturer: result = foo(2) assert result == 2 output = output_capturer.string_io.getvalue() assert_output( output, ( # In first with VariableEntry('x', '2'), VariableEntry('bar1'), VariableEntry('bar2'), VariableEntry('bar3'), VariableEntry('foo'), VariableEntry('qux'), VariableEntry('snoop'), LineEntry('foo(x - 1)'), # In with in recursive call VariableEntry('x', '1'), VariableEntry('bar1'), VariableEntry('bar2'), VariableEntry('bar3'), VariableEntry('foo'), VariableEntry('qux'), VariableEntry('snoop'), LineEntry('foo(x - 1)'), # Call to bar1 from if block outside with VariableEntry('_x', '0'), VariableEntry('qux'), CallEntry('def bar1(_x):'), LineEntry('qux()'), ReturnEntry('qux()'), ReturnValueEntry('None'), # In with in recursive call LineEntry('bar2(x)'), # Call to bar2 from within with VariableEntry('_x', '1'), VariableEntry('qux'), CallEntry('def bar2(_x):'), LineEntry('qux()'), ReturnEntry('qux()'), ReturnValueEntry('None'), # In with in recursive call LineEntry('qux()'), # Call to bar3 from after with VariableEntry('_x', '9'), VariableEntry('qux'), CallEntry('def bar3(_x):'), LineEntry('qux()'), ReturnEntry('qux()'), ReturnValueEntry('None'), # -- Similar to previous few sections, # -- but from first call to foo # In with in first call LineEntry('bar2(x)'), # Call to bar2 from within with VariableEntry('_x', '2'), VariableEntry('qux'), CallEntry('def bar2(_x):'), LineEntry('qux()'), ReturnEntry('qux()'), ReturnValueEntry('None'), # In with in first call LineEntry('qux()'), # Call to bar3 from after with VariableEntry('_x', '9'), VariableEntry('qux'), CallEntry('def bar3(_x):'), LineEntry('qux()'), ReturnEntry('qux()'), ReturnValueEntry('None'), ), )
import torch import pysnooper def large(l): return isinstance(l, list) and len(l) > 5 def print_list_size(l): return 'list(size={})'.format(len(l)) def print_ndarray(a): return 'ndarray(shape={}, dtype={})'.format(a.shape, a.dtype) def print_tensor(tensor): return 'torch.Tensor(shape={}, dtype={}, device={})'.format( tensor.shape, tensor.dtype, tensor.device) custom_repr = ((large, print_list_size), (np.ndarray, print_ndarray), (torch.Tensor, print_tensor)) snooper_config = { 'custom_repr': custom_repr, } my_snooper = pysnooper.snoop(**snooper_config)
def f1(a): with pysnooper.snoop(string_io, depth=4): result1 = f2(a) return result1
def decorate_method_with_pysnooper(method, depth=1, *args, **kwargs): return pysnooper.snoop(depth=depth, *args, **kwargs)(method)
value['total_price'] ) #Throws ValueError, due to total_price bing a negative number value['unit_cost'] = value['total_price'] / value[ 'units_rented'] #there is data in the json that includes 'units_rented' = 0 except ValueError: logger.warning( '"sqrt_total_price" was not able to be attained, total_days was a negative value' ) #(0) except ZeroDivisionError: logger.error('division by zero, units_rented') except AttributeError: logger.error("'data' variable object has no attribute 'values'") return data def save_to_json(filename, data): with open(filename, 'w') as file: json.dump(data, file) if __name__ == "__main__": with pysnooper.snoop(): args = parse_cmd_arguments( ) # add exception for no parameters / warning data = load_rentals_file(args.input) data = calculate_additional_fields(data) save_to_json(args.output, data)
def f1(a): with pysnooper.snoop(string_io, depth=4, normalize=normalize): result1 = f2(a) return result1