Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Python 黑魔法指南 v1.0

The document provides a comprehensive overview of various Python programming concepts and features, including data types, functions, error handling, and built-in functions. It includes code snippets and examples to illustrate the usage of these features. Additionally, it touches on differences between Python 2 and Python 3, as well as best practices in coding.

Uploaded by

bangchen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python 黑魔法指南 v1.0

The document provides a comprehensive overview of various Python programming concepts and features, including data types, functions, error handling, and built-in functions. It includes code snippets and examples to illustrate the usage of these features. Additionally, it touches on differences between Python 2 and Python 3, as well as best practices in coding.

Uploaded by

bangchen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Python

v1.0
2020 05 12
Python
wongbingming@163.com
Github https://github.com/iswbm/magic-python

01.

...
>>> ...
Ellipsis
>>> type(...)
<class 'ellipsis'>

...

>>> Ellipsis
Ellipsis
>>> type(Ellipsis)
<type 'ellipsis'>
>>>

>>> bool(...)
True

>>> id(...)
4362672336
>>> id(...)
4362672336

$ cat demo.py
def func01():
...

def func02():
pass

func01()
func02()

print("ok")

$ python3 demo.py
ok

02. end

__builtins__.end = None

def my_abs(x):
if x > 0:
return x
else:
return -x
end
end

print(my_abs(10))
print(my_abs(-10))

[root@localhost ~]$ python demo.py


10
10

03. zip
[root@localhost ~]# ls -l demo
total 8
-rw-r--r-- 1 root root 30 May 8 19:27 calc.py
-rw-r--r-- 1 root root 35 May 8 19:33 __main__.py
[root@localhost ~]#
[root@localhost ~]# cat demo/__main__.py
import calc

print(calc.add(2, 3))
[root@localhost ~]#
[root@localhost ~]# cat demo/calc.py
def add(x, y):
return x+y
[root@localhost ~]#
[root@localhost ~]# python -m zipfile -c demo.zip demo/*
[root@localhost ~]#

[root@localhost ~]# python demo.zip


5
[root@localhost ~]#

04. :

[root@localhost ~]$ cat demo.py


print("hello "\
"world")
[root@localhost ~]$
[root@localhost ~]$ python demo.py
hello world

>>> str1='\nhello'
>>> print(str1)

hello
>>> str2='\thello' tab
>>> print(str2)
hello

>>> str3="\"
File "<stdin>", line 1
str3="\"
^
SyntaxError: EOL while scanning string literal

>>> str3=r"\"
File "<stdin>", line 1
str3=r"\"
^
SyntaxError: EOL while scanning string literal

05. for
for i in iter(int, 1):pass

int

int()

06. “_”

_
>>> 3 + 4
7
>>> _
7
>>> name=' : Python '
>>> name
' : Python '
>>> _
' : Python '

>>> 3 + 4
7
>>> _
7
>>> print(" : Python ")
ming
>>> _
7

__repr__

# demo.py
class mytest():
def __str__(self):
return "hello"

def __repr__(self):
return "world"

>>> import demo


>>> mt=demo.mytest()
>>> mt
world
>>> print(mt)
hello
>>> _
world

07.

>>> import sys


>>> from pprint import pprint
>>> pprint(sys.path)
['',
'/usr/local/Python3.7/lib/python37.zip',
'/usr/local/Python3.7/lib/python3.7',
'/usr/local/Python3.7/lib/python3.7/lib-dynload',
'/home/wangbm/.local/lib/python3.7/site-packages',
'/usr/local/Python3.7/lib/python3.7/site-packages']
>>>

[wangbm@localhost ~]$ python3 -m site


sys.path = [
'/home/wangbm',
'/usr/local/Python3.7/lib/python37.zip',
'/usr/local/Python3.7/lib/python3.7',
'/usr/local/Python3.7/lib/python3.7/lib-dynload',
'/home/wangbm/.local/lib/python3.7/site-packages',
'/usr/local/Python3.7/lib/python3.7/site-packages',
]
USER_BASE: '/home/wangbm/.local' (exists)
USER_SITE: '/home/wangbm/.local/lib/python3.7/site-packages' (exists)
ENABLE_USER_SITE: True
08. and or

>>>(2 or 3) * (5 and 7)
14 # 2*7

09.

>>> for i in range(2):


... print (i)
...
0
1

>>> ...

>>> import sys


>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>>
>>> sys.ps2 = '---------------- '
>>> sys.ps1 = 'Python >>>'
Python >>>for i in range(2):
---------------- print (i)
----------------
0
1

10.

[root@localhost ~]# cat demo.py


def func():
return "ok",

print(func())
[root@localhost ~]# python3 demo.py
('ok',)

[root@localhost ~]# cat demo.py


for i in range(3):
print i
[root@localhost ~]#
[root@localhost ~]# python demo.py
0
1
2
[root@localhost ~]#
[root@localhost ~]# vim demo.py
[root@localhost ~]#
[root@localhost ~]# cat demo.py
for i in range(3):
print i,
[root@localhost ~]#
[root@localhost ~]# python demo.py
0 1 2
[root@localhost ~]#

11.

def func(item, item_list=[]):


item_list.append(item)
print(item_list)

func('iphone')
func('xiaomi', item_list=['oppo','vivo'])
func('huawei')

['iphone']
['oppo', 'vivo', 'xiaomi']
['iphone', 'huawei']
12.

class Kls():
def public(self):
print('Hello public world!')

def __private(self):
print('Hello private world!')

def call_private(self):
self.__private()

ins = Kls()

#
ins.public()
#
ins.__private()

#
ins.call_private()

#
ins._Kls__private()
ins.call_private()

13.

>>> alist = [0, 1, 2, 3, 4]


>>> alist[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range

>>> alist = [0, 1, 2, 3, 4]


>>> alist[5:]
[]
>>> alist[100:]
[]

14.
\

>>> a = 'talk is cheap,'\


... 'show me the code.'
>>>
>>> print(a)
talk is cheap,show me the code.

[] () {}

>>> my_list=[1,2,3,
... 4,5,6]

>>> my_tuple=(1,2,3,
... 4,5,6)

>>> my_dict={"name": "MING",


... "gender": "male"}

'''

>>> text = '''talk is cheap,


... show me the code'''

15. Python2 print(“”)

print ""

print "hello"
print "hello"
print("hello")
print ("hello")

print("hello")
print ("hello")

16.

# Python2.7
>>> a = "Hello_Python"
>>> id(a)
32045616
>>> id("Hello" + "_" + "Python")
32045616

# Python3.7
>>> a = "Hello_Python"
>>> id(a)
38764272
>>> id("Hello" + "_" + "Python")
32045616
>>> a = "MING"
>>> b = "MING"
>>> a is b
True

# Python2.7
>>> a, b = "MING!", "MING!"
>>> a is b
True

# Python3.7
>>> a, b = "MING!", "MING!"
>>> a is b
False

# Python2.7
>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'
True
>>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'
False

# Python3.7
>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa'
True
>>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa'
True

17. return
>>> def func():
... try:
... return 'try'
... finally:
... return 'finally'
...
>>> func()
'finally'

>>> def func():


... try:
... return 'try'
... finally:
... print('finally')
...
>>>
>>> func()
finally
'try'
>>>

18.
>>> a = -6
>>> b = -6
>>> a is b
False

>>> a = 256
>>> b = 256
>>> a is b
True

>>> a = 257
>>> b = 257
>>> a is b
False

>>> a = 257; b = 257


>>> a is b
True

19. intern
>>> s1="hello"
>>> s2="hello"
>>> s1 is s2
True

# intern
>>> s1="hell o"
>>> s2="hell o"
>>> s1 is s2
False

# 20 intern
>>> s1 = "a" * 20
>>> s2 = "a" * 20
>>> s1 is s2
True

>>> s1 = "a" * 21
>>> s2 = "a" * 21
>>> s1 is s2
False

>>> s1 = "ab" * 10
>>> s2 = "ab" * 10
>>> s1 is s2
True

>>> s1 = "ab" * 11
>>> s2 = "ab" * 11
>>> s1 is s2
False

20. /
>>> ml = [1,2,3,4,5]
>>> ml.reverse()
>>> ml
[5, 4, 3, 2, 1]

mstr1 = 'abc'
ml1 = list(mstr1)
ml1.reverse()
mstr2 = str(ml1)

def my_reverse(str):
if str == "":
return str
else:
return my_reverse(str[1:]) + str[0]

>>> mstr = 'abc'


>>> ml = [1,2,3]
>>> mstr[::-1]
'cba'
>>> ml[::-1]
[3, 2, 1]
21.

>>> import sys


>>> sys.getrecursionlimit()
1000

>>> sys.setrecursionlimit(2000)
>>> sys.getrecursionlimit()
2000

22. FTP

# python2
python -m SimpleHTTPServer 8888

# python3
python3 -m http.server 8888
23. else

def check_item(source_list, target):


for item in source_list:
if item == target:
print("Exists!")
break

else:
print("Does not exist")

check_item(["apple", "huawei", "oppo"], "oppo")


# Exists!

check_item(["apple", "huawei", "oppo"], "vivo")


# Does not exist

def test_try_else(attr1 = None):


try:
if attr1:
pass
else:
raise
except:
print("Exception occurred...")
else:
print("No Exception occurred...")

test_try_else()
# Exception occurred...

test_try_else("ming")
# No Exception occurred...

24.

>>> "aabb".count("a")
2
>>> "aabb".count("b")
2
>>> "aabb".count("ab")
1

>>> "aabb".count("")
5

aabb
>>> (" " * 10).count("")
11
>>>
>>> "" in ""
True
>>>
>>> "" in "M"
True

25.

>>> 5-3
2
>>> 5--3
8
>>> 5+-3
2
>>> 5++3
8
>>> 5---3
2
26.

>>> 100000000 < ""


True
>>> 100000000 < "hello"
True

>>> 100000000 < ""


TypeError: '<' not supported between instances of 'int' and 'str'

27.

# Python2
>>> x = 1
>>> [x for x in range(5)]
[0, 1, 2, 3, 4]
>>> x
4

# Python3
>>> x = 1
>>> [x for x in range(5)]
[0, 1, 2, 3, 4]
>>> x
1

28.

# Python2.7.10
>>> mydict = {str(i):i for i in range(5)}
>>> mydict
{'1': 1, '0': 0, '3': 3, '2': 2, '4': 4}

# Python3.6.7
>>> mydict = {str(i):i for i in range(5)}
>>> mydict
{'0': 0, '1': 1, '2': 2, '3': 3, '4': 4}

29. import

>>> import __hello__


Hello World!

>>> 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.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

antigravity

>>> import antigravity


30. /

# demo.py
a = 1

def add():
a += 1

add()

$ python demo.py
Traceback (most recent call last):
File "demo.py", line 6, in <module>
add()
File "demo.py", line 4, in add
a += 1
UnboundLocalError: local variable 'a' referenced before assignment

a += 1 a
a

$ cat demo.py
a = 1

def output():
print(a)

output()

$ python demo.py
1
31.

>>> valuе = 32
File "<stdin>", line 1
valuе = 32
^
SyntaxError: invalid syntax

>>> valuе = 32
>>> value
11
valuе = 32

е e

>>> ord('е') # cyrillic 'e' (Ye)


1077
>>> ord('e') # latin 'e', as used in English and typed using standard keyboard
101
>>> 'е' == 'e'
False

e
e

32.

\n

>>> str = "a\nb\n"


>>> print(str)
a
b

>>> str.split('\n')
['a', 'b', '']
>>>

splitlines

>>> str.splitlines()
['a', 'b']

33.

import contextlib

@contextlib.contextmanager
def test_context(name):
print('enter, my name is {}'.format(name))
yield

print('exit, my name is {}'.format(name))

with test_context('aaa'):
with test_context('bbb'):
print('========== in main ============')

enter, my name is aaa


enter, my name is bbb
========== in main ============
exit, my name is bbb
exit, my name is aaa

with test_context('aaa'), test_context('bbb'):


print('========== in main ============')

34. += =+

+= =+

# =+
>>> a = [1, 2, 3, 4]
>>> b = a
>>> a = a + [5, 6, 7, 8]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
>>> b
[1, 2, 3, 4]

# +=
>>> a = [1, 2, 3, 4]
>>> b = a
>>> a += [5, 6, 7, 8]
>>> a
[1, 2, 3, 4, 5, 6, 7, 8]
>>> b
[1, 2, 3, 4, 5, 6, 7, 8]

35.

+= *=

#
a = 1 ; a += 1

#
a = 1; a = a + 1

+=

36. x == +x
>>> n1 = 10086
>>> n2 = +n1
>>>
>>> n1 == n2
True

+ <=

>>> from collections import Counter


>>> ct = Counter('abcdbcaa')
>>> ct
Counter({'a': 3, 'b': 2, 'c': 2, 'd': 1})
>>> ct['c'] = 0
>>> ct['d'] = -2
>>>
>>> ct
Counter({'a': 3, 'b': 2, 'c': 0, 'd': -2})
>>>
>>> +ct
Counter({'a': 3, 'b': 2})

37. print

>>> with open('test.log', mode='w') as f:


... print('hello, python', file=f, flush=True)
>>> exit()

$ cat test.log
hello, python
38. site-packages dist-packages

>>> from distutils.sysconfig import get_python_lib


>>> print(get_python_lib())
/usr/lib/python2.7/site-packages

39. argument parameter

"error" parameter

def output_msg(msg):
print(msg)

output_msg("error")
40.

>>> False == False == True


False

if 80 < score <= 90:


print(" ")

>>> False == False and False == True


False

41.

>>> a = [1,2]
>>> b = [3,4]
>>> c = [5,6]
>>>
>>> sum((a,b,c), [])
[1, 2, 3, 4, 5, 6]
42. 8

>>> list01 = [1,2,3]


>>> list02 = [4,5,6]
>>> list03 = [7,8,9]
>>>
>>> list01 + list02 + list03
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

itertools.chain()

>>> from itertools import chain


>>> list01 = [1,2,3]
>>> list02 = [4,5,6]
>>> list03 = [7,8,9]
>>>
>>> list(chain(list01, list02, list03))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

>>> list01 = [1,2,3]


>>> list02 = [4,5,6]
>>>
>>> [*list01, *list02]
[1, 2, 3, 4, 5, 6]
>>>

>>> list01 = [1,2,3]


>>> list02 = [4,5,6]
>>>
>>> list01.extend(list02)
>>> list01
[1, 2, 3, 4, 5, 6]

>>> list01 = [1,2,3]


>>> list02 = [4,5,6]
>>> list03 = [7,8,9]
>>>
>>> [x for l in (list01, list02, list03) for x in l]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

>>> list01 = [1,2,3]


>>> list02 = [4,5,6]
>>> list03 = [7,8,9]
>>>
>>> from heapq import merge
>>>
>>> list(merge(list01, list02, list03))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

>>> list01 = [2,5,3]


>>> list02 = [1,4,6]
>>> list03 = [7,9,8]
>>>
>>> from heapq import merge
>>>
>>> list(merge(list01, list02, list03))
[1, 2, 4, 5, 3, 6, 7, 9, 8]
>>>

sorted(itertools.chain(*iterables))

__add__
__add__

>>> list01 = [1,2,3]


>>> list02 = [4,5,6]
>>>
>>> list01 + list02
[1, 2, 3, 4, 5, 6]
>>>
>>>
>>> list01.__add__(list02)
[1, 2, 3, 4, 5, 6]
>>>

>>> list01 = [1,2,3]


>>> list02 = [4,5,6]
>>> list03 = [7,8,9]
>>>
>>> from functools import reduce
>>> reduce(list.__add__, (list01, list02, list03))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

>>> list01 = [1,2,3]


>>> list02 = [4,5,6]
>>> list03 = [7,8,9]
>>>
>>> def merge(*lists):
... for l in lists:
... yield from l
...
>>> list(merge(list01, list02, list03))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>

43.
clean()
atexit.register(clean_1, 1, 2, 3='xxx')

os._exit()

44. 8

>>> profile = {"name": "xiaoming", "age": 27}


>>> ext_info = {"gender": "male"}
>>>
>>> profile.update(ext_info)
>>> print(profile)
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}
>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> from copy import deepcopy
>>>
>>> full_profile = deepcopy(profile)
>>> full_profile.update(ext_info)
>>>
>>> print(full_profile)
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}
>>> print(profile)
{"name": "xiaoming", "age": 27}

** {}

>>> profile = {"name": "xiaoming", "age": 27}


>>> ext_info = {"gender": "male"}
>>>
>>> full_profile01 = {**profile, **ext_info}
>>> print(full_profile01)
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}
>>>
>>> full_profile02 = dict(**profile, **ext_info)
>>> print(full_profile02)
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

dict(**profile, **ext_info)

>>> dict((("name", "xiaoming"), ("age", 27), ("gender", "male")))


{'name': 'xiaoming', 'age': 27, 'gender': 'male'}
itertools.chain()

>>> import itertools


>>>
>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>>
>>> dict(itertools.chain(profile.items(), ext_info.items()))
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

ChainMap itertools

>>> from collections import ChainMap


>>>
>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info = {"gender": "male"}
>>>
>>> dict(ChainMap(profile, ext_info))
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

>>> from collections import ChainMap


>>>
>>> profile = {"name": "xiaoming", "age": 27}
>>> ext_info={"age": 30}
>>> dict(ChainMap(profile, ext_info))
{'name': 'xiaoming', 'age': 27}

|
items

>>> profile = {"name": "xiaoming", "age": 27}


>>> ext_info = {"gender": "male"}
>>>
>>> full_profile = dict(profile.items() | ext_info.items())
>>> full_profile
{'gender': 'male', 'age': 27, 'name': 'xiaoming'}

>>> profile = {"name": "xiaoming", "age": 27}


>>> ext_info = {"gender": "male"}
>>>
>>> dict(list(profile.items()) + list(ext_info.items()))
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

>>> profile = {"name": "xiaoming", "age": 27}


>>> ext_info = {"gender": "male"}
>>>
>>> dict(profile.items() + ext_info.items())
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

>>> profile = {"name": "xiaoming", "age": 27}


>>> ext_info = {"gender": "male"}
>>>
>>> {k:v for d in [profile, ext_info] for k,v in d.items()}
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

>>> profile = {"name": "xiaoming", "age": 27}


>>> ext_info = {"gender": "male"}
>>>
>>> profile | ext_info
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}
>>>
>>> ext_info | profile
{'gender': 'male', 'name': 'xiaoming', 'age': 27}
>>>
>>>

| |=

>>> ext_info |= profile


>>> ext_info
{'gender': 'male', 'name': 'xiaoming', 'age': 27}
>>>
>>>
>>> profile |= ext_info
>>> profile
{'name': 'xiaoming', 'age': 27, 'gender': 'male'}

45.
if age > 18:
return " "
else:
return " "

<on_true> if <condition> else <on_false>

>>> age1 = 20
>>> age2 = 17
>>>
>>>
>>> msg1 = " " if age1 > 18 else " "
>>> print msg1

>>>
>>> msg2 = " " if age2 > 18 else " "
>>> print msg2

>>>

<condition> and <on_true> or <on_false>


>>> msg1 = age1 > 18 and " " or " "
>>> msg2 = " " if age2 > 18 else " "
>>>
>>> print(msg1)

>>>
>>> print(msg2)

(<on_true>, <on_false>)[condition]

>>> msg1 = (" ", " ")[age1 > 18]


>>> print(msg1)

>>>
>>>
>>> msg2 = (" ", " ")[age2 > 18]
>>> print(msg2)

(lambda: <on_false>, lambda:<on_true>)[<condition>]()

>>> msg1 = (lambda:" ", lambda:" ")[age1 > 18]()


>>> print(msg1)
>>>
>>> msg2 = (lambda:" ", lambda:" ")[age2 > 18]()
>>> print(msg2)

{True: <on_true>, False: <on_false>}[<condition>]

>>> msg1 = {True: " ", False: " "}[age1 > 18]
>>> print(msg1)

>>>
>>> msg2 = {True: " ", False: " "}[age2 > 18]
>>> print(msg2)

((<condition>) and (<on_true>,) or (<on_false>,))[0]

>>> msg1 = ((age1 > 18) and (" ",) or (" ",))[0]
>>> print(msg1)

>>>
>>> msg2 = ((age2 > 18) and (" ",) or (" ",))[0]
>>> print(msg2)
46. /usr/bin/env python

#!/usr/bin/python

#!/usr/bin/env python

/usr/bin/python python
python
#! /usr/bin/python

python xx.py

python

#!/usr/bin/python

!/usr/bin/env python

env python
env python env | grep PATH

/usr/bin/python PATH
/usr/local/sbin
/usr/bin/python

#!/usr/bin/env python
/usr/bin/python

47.

pip install --user pkg


# requests
[root@localhost ~]$ pip list | grep requests
[root@localhost ~]$ su - wangbm

#
[wangbm@localhost ~]$ pip list | grep requests
[wangbm@localhost ~]$ pip install --user requests
[wangbm@localhost ~]$ pip list | grep requests
requests (2.22.0)
[wangbm@localhost ~]$

# Location requests
[wangbm@localhost ~]$ pip show requests
---
Metadata-Version: 2.1
Name: requests
Version: 2.22.0
Summary: Python HTTP for Humans.
Home-page: http://python-requests.org
Author: Kenneth Reitz
Author-email: me@kennethreitz.org
Installer: pip
License: Apache 2.0
Location: /home/wangbm/.local/lib/python2.7/site-packages
[wangbm@localhost ~]$ exit
logout

# wangbm root requests


[root@localhost ~]$ pip list | grep requests
[root@localhost ~]$

48. defer

import "fmt"

func myfunc() {
fmt.Println("B")
}
func main() {
defer myfunc()
fmt.Println("A")
}

A
B

import contextlib

def callback():
print('B')

with contextlib.ExitStack() as stack:


stack.callback(callback)
print('A')

A
B

49.
@functools.lru_cache(maxsize=None, typed=False)

from functools import lru_cache

@lru_cache(None)
def add(x, y):
print("calculating: %s + %s" % (x, y))
return x + y

print(add(1, 2))
print(add(1, 2))
print(add(2, 3))

calculating: 1 + 2
3
3
calculating: 2 + 3
5

50.
import contextlib

log_file="/var/log/you.log"

def you_task():
pass

@contextlib.contextmanager
def close_stdout():
raw_stdout = sys.stdout
file = open(log_file, 'a+')
sys.stdout = file

yield

sys.stdout = raw_stdout
file.close()

with close_stdout():
you_task()

You might also like