"Python"의 두 판 사이의 차이

ph
이동: 둘러보기, 검색
 
(같은 사용자의 중간 판 8개는 보이지 않습니다)
1번째 줄: 1번째 줄:
 +
== pdb howto ==
 +
[https://realpython.com/python-debugging-pdb/]
 +
 +
==start debugger automatically on error==
 +
python -m pdb -c continue myscript.py
 +
[https://stackoverflow.com/a/2438834/766330]
 +
 +
==print all variables==
 +
locals()
 +
[https://stackoverflow.com/questions/21961693/how-to-print-all-variables-values-when-debugging-python-with-pdb-without-specif]
 +
 
==current time as str==
 
==current time as str==
 
  import datetime
 
  import datetime
 
  cur = datetime.datetime.now()
 
  cur = datetime.datetime.now()
 
  cur.strftime('%m%d%H%M')
 
  cur.strftime('%m%d%H%M')
https://tecadmin.net/get-current-date-time-python/
+
[https://tecadmin.net/get-current-date-time-python/]
  
 
==simple line plots==
 
==simple line plots==
360번째 줄: 371번째 줄:
 
스트링format에서, %s로 유니코드를 받으려면 format string도 unicode여야 한다. <code>u'%s'</code> 이렇게. 그래서 섞어 써야 할 때는, ①format string을 놔두고, 유니코드를 utf8로 디코드 해서 넘기든지, ② format string을 unicode로 주고 utf8문자열에 죄다 <code>decode('utf-8')</code>을 붙인다.
 
스트링format에서, %s로 유니코드를 받으려면 format string도 unicode여야 한다. <code>u'%s'</code> 이렇게. 그래서 섞어 써야 할 때는, ①format string을 놔두고, 유니코드를 utf8로 디코드 해서 넘기든지, ② format string을 unicode로 주고 utf8문자열에 죄다 <code>decode('utf-8')</code>을 붙인다.
  
시간이 너무 남아돌면 기본 매뉴얼[https://docs.python.org/2/howto/unicode.html]을 읽어보는것도...
+
시간이 너무 남아돌면 기본 매뉴얼[https://docs.python.org/2/howto/unicode.html]을 훑어본다.
 +
 
 +
[https://stackoverflow.com/a/492711/766330 stackoverflow]에 훌륭한 규칙이 나옴: A rule of thumb is: Always use Unicode internally. Decode what you receive, and encode what you send. 받는건 무조건 decode, 내보내는건 무조건 encode. 내부는 유니코드로 고정이기 때문.
  
 
==Reading another encoding from a file==
 
==Reading another encoding from a file==
461번째 줄: 474번째 줄:
  
 
https://stackoverflow.com/a/16068078/766330
 
https://stackoverflow.com/a/16068078/766330
 +
 +
==pdf file merge==
 +
  from PyPDF2 import PdfMerger
 +
 
 +
  pdfs = ['file1.pdf', 'file2.pdf', 'file3.pdf', 'file4.pdf']
 +
 
 +
  merger = PdfMerger()
 +
 
 +
  for pdf in pdfs:
 +
      merger.append(pdf)
 +
 
 +
  merger.write("result.pdf")
 +
  merger.close()
 +
 +
page range를 줄 수도 있다고 함. 별로 직관적이지는 않아보임
 +
 +
그냥 파일 여러개를 합하는것을 명령어로 할 수 있는 것:
 +
  python -m fitz join -o result.pdf file1.pdf file2.pdf file3.pdf
 +
 +
PyMuPdf[https://github.com/pymupdf/PyMuPDF]참고
 +
 +
[https://stackoverflow.com/a/37945454/766330]
 +
 +
==images to pdf==
 +
  image_list = [im_2, im_3, im_4]
 +
  im_1.save(r'C:\Users\Ron\Desktop\Test\my_images.pdf', save_all=True, append_images=image_list)
 +
 +
PIL.Image에 이미 기능이 있었음.
 +
[https://datatofish.com/images-to-pdf-python/]
 +
 +
==natural sort==
 +
use <kbd>natsorted</kbd>
 +
<pre>
 +
>>> from natsort import natsorted, ns
 +
>>> x = ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']
 +
>>> natsorted(x, key=lambda y: y.lower())
 +
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
 +
>>> natsorted(x, alg=ns.IGNORECASE)  # or alg=ns.IC
 +
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
 +
</pre>
 +
[https://stackoverflow.com/a/18415320/766330]

2023년 2월 20일 (월) 13:10 기준 최신판

pdb howto

[1]

start debugger automatically on error

python -m pdb -c continue myscript.py

[2]

print all variables

locals()

[3]

current time as str

import datetime
cur = datetime.datetime.now()
cur.strftime('%m%d%H%M')

[4]

simple line plots

plt.style.use('seaborn-whitegrid')

[5]

flatten all lists recursively

li=[[1,[[2]],[[[3]]]],[['4'],{5:5}]]
flatten=lambda l: sum(map(flatten,l),[]) if isinstance(l,list) else [l]
print flatten(li)

[6]

다음과 같은 기묘한 속성 때문이다

>>> [] + [1]
[1]
>>> sum([[1]], [2])
[2, 1]
>>> sum([[1]], [])
[1]

다음을 실행하면,

depth = 0
def flatten_(x):
    global depth
    depth += 1
    r = None
    if isinstance(x, list):
        print('>'*depth, 'list:', x)
        y = sum(map(flatten_,x), [])
        r = y
    else:
        print('>'*depth, 'not list:',x)
        r = [x]
    print('<'*depth, 'returning', r)
    depth -= 1
    return r
    
li=[[1,[[2]],[[[3]]]],[['4'],{5:5}]]
flatten_(li)

결과는,

> list: [[1, [[2]], [[[3]]]], [['4'], {5: 5}]]
>> list: [1, [[2]], [[[3]]]]
>>> not list: 1
<<< returning [1]
>>> list: [[2]]
>>>> list: [2]
>>>>> not list: 2
<<<<< returning [2]
<<<< returning [2]
<<< returning [2]
>>> list: [[[3]]]
>>>> list: [[3]]
>>>>> list: [3]
>>>>>> not list: 3
<<<<<< returning [3]
<<<<< returning [3]
<<<< returning [3]
<<< returning [3]
<< returning [1, 2, 3]
>> list: [['4'], {5: 5}]
>>> list: ['4']
>>>> not list: 4
<<<< returning ['4']
<<< returning ['4']
>>> not list: {5: 5}
<<< returning [{5: 5}]
<< returning ['4', {5: 5}]
< returning [1, 2, 3, '4', {5: 5}]

재정의

이 페이지에 거의 다 있는듯함.
나열하면 다음과 같다.

__abs__             __add__             __aenter__          __aexit__           
__aiter__           __and__             __anext__           __annotations__     
__await__           __bases__           __bool__            __bytes__           
__call__            __ceil__            __class__           __classcell__       
__closure__         __code__            __complex__         __contains__        
__defaults__        __del__             __delattr__         __delete__          
__delitem__         __dict__            __dir__             __divmod__          
__doc__             __enter__           __eq__              __exit__            
__file__            __float__           __floor__           __floordiv__        
__format__          __func__            __future__          __ge__              
__get__             __getattr__         __getattribute__    __getitem__         
__globals__         __gt__              __hash__            __iadd__            
__iand__            __ifloordiv__       __ilshift__         __imatmul__         
__imod__            __import__          __imul__            __index__           
__init__            __instancecheck__   __int__             __invert__          
__ior__             __ipow__            __irshift__         __isub__            
__iter__            __itruediv__        __ixor__            __kwdefaults__      
__le__              __len__             __lshift__          __lt__              
__matmul__          __missing__         __mod__             __module__          
__mro__             __mul__             __name__            __ne__              
__neg__             __new__             __next__            __objclass__        
__or__              __pos__             __pow__             __prepare__         
__qualname__        __radd__            __rand__            __rdivmod__         
__repr__            __reversed__        __rfloordiv__       __rlshift__         
__rmatmul__         __rmod__            __rmul__            __ror__             
__round__           __rpow__            __rrshift__         __rshift__          
__rsub__            __rtruediv__        __rxor__            __self__            
__set__             __setattr__         __setitem__         __slots__           
__str__             __sub__             __subclasscheck__   __traceback__       
__truediv__         __trunc__           __weakref__         __xor__  

grep -ho -e '__[a-z]*__' x.txt | sort -u | xargs -n 4 printf '%-20s%-20s%-20s%-20s\n'

2.7과 3.6 동시에 쓰기

참고링크 참고링크2

아래로 만들고,

conda create -n py36 python=3.6 anaconda

아래로 activate

source activate py36

환경 리스트

conda env list

__call__ 클래스로도, 함수로도 쓸 수 있음.

The first is used to initialise newly created object, and receives arguments used to do that:

    class Foo:
        def __init__(self, a, b, c):
            # ...

    x = Foo(1, 2, 3) # __init__

The second implements function call operator.

    class Foo:
        def __call__(self, a, b, c):
            # ...

    x = Foo()
    x(1, 2, 3) # __call__

[7]

jupyter notebook matplotlib on OSX

Insert below code at the head of the note.

import matplotlib as mpl 
mpl.use('TkAgg')

[8]

한글외 문자 제거

hangul = re.compile('[^ ㄱ-ㅣ가-힣]+') # 한글과 띄어쓰기를 제외한 모든 글자
# hangul = re.compile('[^ \u3131-\u3163\uac00-\ud7a3]+')  # 위와 동일
result = hangul.sub('', target_text) # 한글과 띄어쓰기를 제외한 모든 부분을 제거

http://jokergt.tistory.com/52

ternary operator

a if condition else b

[9]

print color to terminal stdout

print('\x1b[6;30;42m' + 'Success!' + '\x1b[0m')

[10]

ansi

RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
LIGHT_PURPLE = '\033[94m'
PURPLE = '\033[95m'
END = '\033[0m'

코드로도 된다고 하는데 그럴필요까지야.

from __future__ import print_function
from colorprint import *

print('Hello', 'world', color='blue', end='', sep=', ')
print('!', color='red', format=['bold', ‘blink'])

[11]

filter

filter(None, list)

None이나 \(0\)을 제외하게 된다.[12]

ipython (jupyter notebook)

load a file

%load f.py

save current cell to a file

%%writefile f.py

shell command

!ls
!cat “file” 

[13]

Multiple input stream

import fileinput
for line in fileinput.input():
    process(line)

https://docs.python.org/2/library/fileinput.html#module-fileinput

file position

def skip_comments(f):
    while True:
        pos = f.tell()
        line = f.readline().strip()
        if not line.startswith('#'):
            f.seek(pos) #rewind
            break

tell로 현재 위치를 얻고, seek로 set.

>>> f = open('workfile', 'r+')
>>> f.write('0123456789abcdef')
>>> f.seek(5)      # Go to the 6th byte in the file
>>> f.read(1)
'5'
>>> f.seek(-3, 2)  # Go to the 3rd byte before the end
>>> f.read(1)
'd'

https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects


Interactive session detection

sys.stdin.isatty()

http://stackoverflow.com/a/7576567/766330


Temporary file or directory

tempfile.TemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None]]]]]) [14]

임시파일을 만든다. 아래를 쓸것.

tempfile.NamedTemporaryFile([mode='w+b'[, bufsize=-1[, suffix=''[, prefix='tmp'[, dir=None[, delete=True]]]]]]) [15]

위와 동일하나 visible name의 파일을 만든다. 이름은 반환값의 name속성으로 받을 수 있다.
주의할점은, delete속성의 기본값이 True여서 쓰여진 후 곧바로 지워진다. 계속 쓰려면 해당속성을 False로 해야 한다.

tempfile.mkdtemp([suffix=''[, prefix='tmp'[, dir=None]]]) [16]

임시디렉토리를 만들고, 자동으로 지우지 않는다.

Check syntax without running

python -m py_compile script.py

http://stackoverflow.com/a/8437597/766330


Time

current time

>>> import time
>>> time.time()
1491792653.410371
>>> import datetime
>>> datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')
'2017-04-10 11:51:17'  
>>> datetime.datetime.utcnow()
datetime.datetime(2017, 4, 10, 2, 51, 34, 356682)
>>> datetime.datetime.now()
datetime.datetime(2017, 4, 10, 11, 51, 36, 572681)
>>> datetime.datetime.now().strftime("%A, %d. %B %Y %I:%M%p")
'Monday, 10. April 2017 11:51AM'

[17]
if you want UTC, use utcfromtimestamp instead of fromtimestamp [18]

yesterday

>>> from datetime import date, timedelta
>>> yesterday = date.today() - timedelta(1)
>>> print yesterday.strftime('%m%d%y')
'110909'

[19]

strftime format manual


String replace

str.replace

str.replace(old, new[, max]) [20]

re.sub

>>> re.sub(r'def\s+([a-zA-Z_][a-zA-Z_0-9]*)\s*\(\s*\):',
 ...        r'static PyObject*\npy_\1(void)\n{',
 ...        'def myfunc():')
 'static PyObject*\npy_myfunc(void)\n{' [21]

commented version example

line = re.sub(r"""
  (?x) # Use free-spacing mode.
  <    # Match a literal '<'
  /?   # Optionally match a '/'
  \[   # Match a literal '['
  \d+  # Match one or more digits
  >    # Match a literal '>'
  """, "", line) [22]

is and ==

is is identity testing, == is equality testing. what happens in your code would be emulated in the interpreter like this:

>>> a = 'pub'
>>> b = ''.join(['p', 'u', 'b'])
>>> a == b
True
>>> a is b
False

[23]


Access index in for loop

enumerate

for idx, val in enumerate(ints):
   print(idx, val)

[24]

Max integer

sys.maxint

[25]

python 3에서는 안된다고 한다. 어차피 안쓰니 상관없지만 그래서 다음과 같이 한다고.

import sys
max = sys.maxsize
min = -sys.maxsize

[26]

다음도 간단하고 좋은 것 같다. 2,3에서 모두 동작

float('inf')
float('-inf')

[27]

Argument parsing

use argparse


range by step

>>> step = .1
>>> N = 10     # number of data points
>>> [ x / pow(step, -1) for x in range(0, N + 1) ]
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

[28]


File existence

os.path.exists(file_path)

[29] [30]


Define source code encoding

첫째나 둘째줄에,

# coding=<encoding name>

보통 에디터들은 다음 형식을 이해함.

#!/usr/bin/python
# -*- coding: <encoding name> -*-

혹은

#!/usr/bin/python
# vim: set fileencoding=<encoding name> :

정확히는, 첫째나 둘째줄이 아래 정규식에 맞아야 함.

^[ \t\v]*#.*?coding[:=][ \t]*([-_.a-zA-Z0-9]+)

https://www.python.org/dev/peps/pep-0263/

encoding

기본적으로 파이썬은 유니코드를 사용한다. encode/decode할 때, encode하면 유니코드로부터 다른 인코딩으로 가고, decode하면 다른 인코딩으로부터 유니코드로 온다는 얘기. 그래서 unicode().decode()는 매우 쓸데가 없다. [31] 보통은 기본 인코딩을 utf8로 쓰므로 파이썬 코드상에서 가끔 한글이 이상한 동작을 보이면 다 decode('utf-8')붙여주면 된다. 하이픈 없이 utf8이라고 써도 된다.

주의할점은, encode를 부르면 암묵적으로 decode가 먼저 불린다. 따라서 (쓸일도 거의 없지만) encode할 때는 원래 문자열을 decode해주는 것이 안전하다. 안해주면 ascii codec으로 디코딩을 먼저 시도하는데, 한글의 경우는 잘 안되므로 UnicodeEncodeError: 'ascii' codec can't encode characters in position blabla: ordinal not in range(128) 요런 친숙한(?) 에러가 난다. 일단 유니코드로 다 바꾸고 다른 인코딩으로 넘어간다고 생각하면 됨. [32]

스트링format에서, %s로 유니코드를 받으려면 format string도 unicode여야 한다. u'%s' 이렇게. 그래서 섞어 써야 할 때는, ①format string을 놔두고, 유니코드를 utf8로 디코드 해서 넘기든지, ② format string을 unicode로 주고 utf8문자열에 죄다 decode('utf-8')을 붙인다.

시간이 너무 남아돌면 기본 매뉴얼[33]을 훑어본다.

stackoverflow에 훌륭한 규칙이 나옴: A rule of thumb is: Always use Unicode internally. Decode what you receive, and encode what you send. 받는건 무조건 decode, 내보내는건 무조건 encode. 내부는 유니코드로 고정이기 때문.

Reading another encoding from a file

<shl> import codecs f = codecs.open('unicode.rst', encoding='utf-8') for line in f:

   print repr(line)

</shl> https://stackoverflow.com/a/147756/766330

randint

from random import randint
print(randint(0,9))

0~9 inclusive
https://docs.python.org/2/library/random.html#random.randint


groupby example

from itertools import groupby

things = [("animal", "bear"), ("animal", "duck"), ("plant", "cactus"), ("vehicle", "speed boat"), ("vehicle", "school bus")]

for key, group in groupby(things, lambda x: x[0]):
    for thing in group:
        print "A %s is a %s." % (thing[1], key)
    print " "

output

A bear is a animal.
A duck is a animal.

A cactus is a plant.

A speed boat is a vehicle.
A school bus is a vehicle.

http://stackoverflow.com/a/7286/766330


Suppress scientific notation

use %f

'%f' % (x/y)

http://stackoverflow.com/a/658777/766330


To ignore exception

except:
    pass

http://stackoverflow.com/a/574734/766330


Delete items from a dictionary while iterating over it

iteration중에는 지울 수 없다. 두번 돌아야 함.

remove = [k for k in mydict if k == val]
for k in remove: del mydict[k]

http://stackoverflow.com/a/5385196/766330

Print without newline

import sys
sys.stdout.write('.')

http://stackoverflow.com/a/493399/766330

if else in list comprehension

[ unicode(x.strip()) if x is not None else '' for x in row ]

http://stackoverflow.com/a/4260304/766330

filtering a dictionary according to an arbitrary condition

use dict comprehension

{k: v for k, v in points.iteritems() if v[0] < 5 and v[1] < 5}

https://stackoverflow.com/a/16589453/766330

Executing multi-line statements within PDB

(pdb) !import code; code.interact(local=vars()) 
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) 
[GCC 4.4.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> 

https://stackoverflow.com/a/8387484/766330

Converting a IPython Notebook into a Python file via commandline

$ jupyter nbconvert --to script [YOUR_NOTEBOOK].ipynb

or in ipython notebook

!jupyter nbconvert --to script [YOUR_NOTEBOOK].ipynb

https://stackoverflow.com/a/19779226/766330

Write float(or int) to a binary file

import struct
s = struct.pack('f'*len(floats), *floats)
f = open('file','wb')
f.write(s)
f.close()

To read this from C, refer here

https://stackoverflow.com/a/807881/766330

cross reference between files

Use following statements according to appropriate order

from __main__ import *

https://stackoverflow.com/a/16068078/766330

pdf file merge

 from PyPDF2 import PdfMerger
 
 pdfs = ['file1.pdf', 'file2.pdf', 'file3.pdf', 'file4.pdf']
 
 merger = PdfMerger()
 
 for pdf in pdfs:
     merger.append(pdf)
 
 merger.write("result.pdf")
 merger.close()

page range를 줄 수도 있다고 함. 별로 직관적이지는 않아보임

그냥 파일 여러개를 합하는것을 명령어로 할 수 있는 것:

 python -m fitz join -o result.pdf file1.pdf file2.pdf file3.pdf

PyMuPdf[34]참고

[35]

images to pdf

 image_list = [im_2, im_3, im_4]
 im_1.save(r'C:\Users\Ron\Desktop\Test\my_images.pdf', save_all=True, append_images=image_list)

PIL.Image에 이미 기능이 있었음. [36]

natural sort

use natsorted

>>> from natsort import natsorted, ns
>>> x = ['Elm11', 'Elm12', 'Elm2', 'elm0', 'elm1', 'elm10', 'elm13', 'elm9']
>>> natsorted(x, key=lambda y: y.lower())
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']
>>> natsorted(x, alg=ns.IGNORECASE)  # or alg=ns.IC
['elm0', 'elm1', 'Elm2', 'elm9', 'elm10', 'Elm11', 'Elm12', 'elm13']

[37]