<Python> 関数名と行番号を取得する。

デバックdebugしてる時に、関数名function nameと行番号line numberを表示したくなったので、ググった。

sys._getfram()ちゅうやつでできるらしい。例。

In [92]: import sys

In [93]: def hage():
    ...:     print(sys._getframe().f_code.co_name)
    ...:     print(sys._getframe().f_code.co_filename)
    ...:     print(sys._getframe().f_code.co_firstlineno)
    ...:     print(sys._getframe().f_code.co_code)
    ...:     print(sys._getframe().f_lineno)
    ...:     for i in dir(sys._getframe().f_code):
    ...:         print('{} {}'.format(i, getattr(sys._getframe(), i, '-')))
    ...:         

In [94]: hage()
hage
<ipython-input-93-7d9960568d3f>
1
b't\x00t\x01j\x02\x83\x00j\x03j\x04\x83\x01\x01\x00t\x00t\x01j\x02\x83\x00j\x03j\x05\x83\x01\x01\x00t\x00t\x01j\x02\x83\x00j\x03j\x06\x83\x01\x01\x00t\x00t\x01j\x02\x83\x00j\x03j\x07\x83\x01\x01\x00t\x00t\x01j\x02\x83\x00j\x08\x83\x01\x01\x00x2t\tt\x01j\x02\x83\x00j\x03\x83\x01D\x00] }\x00t\x00d\x01j\n|\x00t\x0bt\x01j\x02\x83\x00|\x00d\x02\x83\x03\x83\x02\x83\x01\x01\x00q^W\x00d\x00S\x00'
6
__class__ <class 'frame'>
__delattr__ <method-wrapper '__delattr__' of frame object at 0x00000000071461B8>
__dir__ <built-in method __dir__ of frame object at 0x00000000071461B8>
__doc__ None
__eq__ <method-wrapper '__eq__' of frame object at 0x00000000071461B8>
__format__ <built-in method __format__ of frame object at 0x00000000071461B8>
__ge__ <method-wrapper '__ge__' of frame object at 0x00000000071461B8>
__getattribute__ <method-wrapper '__getattribute__' of frame object at 0x00000000071461B8>
__gt__ <method-wrapper '__gt__' of frame object at 0x00000000071461B8>
__hash__ <method-wrapper '__hash__' of frame object at 0x00000000071461B8>
__init__ <method-wrapper '__init__' of frame object at 0x00000000071461B8>
__init_subclass__ <built-in method __init_subclass__ of type object at 0x000000001DA38550>
__le__ <method-wrapper '__le__' of frame object at 0x00000000071461B8>
__lt__ <method-wrapper '__lt__' of frame object at 0x00000000071461B8>
__ne__ <method-wrapper '__ne__' of frame object at 0x00000000071461B8>
__new__ <built-in method __new__ of type object at 0x000000001DA3C580>
__reduce__ <built-in method __reduce__ of frame object at 0x00000000071461B8>
__reduce_ex__ <built-in method __reduce_ex__ of frame object at 0x00000000071461B8>
__repr__ <method-wrapper '__repr__' of frame object at 0x00000000071461B8>
__setattr__ <method-wrapper '__setattr__' of frame object at 0x00000000071461B8>
__sizeof__ <built-in method __sizeof__ of frame object at 0x00000000071461B8>
__str__ <method-wrapper '__str__' of frame object at 0x00000000071461B8>
__subclasshook__ <built-in method __subclasshook__ of type object at 0x000000001DA38550>
co_argcount -
co_cellvars -
co_code -
co_consts -
co_filename -
co_firstlineno -
co_flags -
co_freevars -
co_kwonlyargcount -
co_lnotab -
co_name -
co_names -
co_nlocals -
co_stacksize -
co_varnames -

他にも、inspectモジュールでもできるらしいが、まあ、これでできたので、良しとする。

参考。
qiita.com

qiita.com

t2y.hatenablog.jp

<logging, Python> ipythonでのlogging

ちと、threadingを使っていたら、どのスレッドが何しているのか?知りたくなり、ロギングloggingしてみた。
したら、ipythonでは、ちと一工夫必要だったのでメモっち。

簡単にいうと、下記をスクリプトに盛り込む。

import logging
logging.disable(logging.FATAL)
# logging.disable(logging.NOTSET)
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
logging.basicConfig(format='[%(asctime)s] %(levelname)s %(process)d %(thread)d %(threadName)s %(lineno)d %(funcName)s %(message)s', level=logging.DEBUG)

logging.basicConfig(level=logging.DEBUG)だけでは、levelDEBUGにならず、 logging.debug('hage')が出力されない。

なので、ロガーloggerオブジェクトを生成して、.setLevel(logging.DEBUG)が必要。
どうしてかは、難しいので、よくわからんが、、、

参考にさせてもらったところ。
note.crohaco.net

http://momijiame.tumblr.com/post/41503983502/python-の-logging-力を高める
momijiame.tumblr.com

d.hatena.ne.jp

threading – スレッドによる並列処理を管理する - Python Module of the Week

<tempfile, Python> ファイルからの読み出しはseek(0)がいる。

テンプファイルtempfileを使った時にちとはまったので、メモ。
tempfileを使って、一時的なファイルを作成し、その内容を読みだす場合、seek(0)しないといけん。

なんにもしないと、、

In [1]: import tempfile

In [6]: with tempfile.TemporaryFile(prefix='tempfile') as f:
   ...:     f.write('hogehoge'.encode('utf-8'))
   ...:     r = f.read()
   ...:     print(r)
   ...:     
b''

てな感じで返ってこない。

で、seek(0)すると、

In [7]: with tempfile.TemporaryFile(prefix='tempfile') as f:
   ...:     f.write('hogehoge'.encode('utf-8'))
   ...:     f.seek(0)
   ...:     r = f.read()
   ...:     print(r)
   ...:     
b'hogehoge'

やっほーう。 返ってきたよ!

ふと、、リードread()した結果は、バイトbyteっぽいから、デコードdecodeしてみた。

In [8]: with tempfile.TemporaryFile(prefix='tempfile') as f:
   ...:     f.write('hogehoge'.encode('utf-8'))
   ...:     f.seek(0)
   ...:     r = f.read()
   ...:     print(r.decode('utf-8'))
   ...:     
hogehoge

お世話になったところ。
tempfile – 一時的なファイルシステムリソースを作成する - Python Module of the Week

<datetime, Python> 文字列をパースしてdatetimeオブジェクト作って、エポックタイムにする。

過去記事の書き換え&再投稿。

文字列stringをパースparseしてdatetimeオブジェクト作って、エポックタイムepoc timeにする。

In [1]: from datetime import datetime as dt

In [2]: dt.strptime('07-25-18 14:25', '%m-%d-%y %H:%M')
Out[2]: datetime.datetime(2018, 7, 25, 14, 25)

In [3]: import time

In [4]: dt.strptime('07-25-18 14:25', '%m-%d-%y %H:%M').timetuple()
Out[4]: time.struct_time(tm_year=2018, tm_mon=7, tm_mday=25, tm_hour=14, tm_min=25, tm_sec=0, tm_wday=2, tm_yday=206, tm_isdst=-1)

In [6]: int(time.mktime(dt.strptime('07-25-18 14:25', '%m-%d-%y %H:%M').timetuple()))
Out[6]: 1532496300

epochtime/unixtimeにするには、

import time
int( time.mktime ( d.timetuple() ) )

か、

import dateutil.parser as parser
parser.parse( day )

でいける。 これで float daysフォーマット (0001-01-01 UTC から始まる日付カウント)になる。

過去記事。
nekoyukimmm.hatenablog.com

参考。
qiita.com

<pip, Python> SSLerrorしても、無理やりインストールする。

Proxy環境化で、SSL Errorがでて、pip installがこけた時でも、無理やりインストールする。

> pip install pyvirtualdisplay
Collecting pyvirtualdisplay
  Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError(SSLError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:833)'),)': /packages/39/37/f285403a09cc261c56b6574baace1bdcf4b8c7428c8a7239cbba137bc0eb/PyVirtualDisplay-0.2.1.tar.gz

-trusted-hostを使う。

>pip install --trusted-host files.pythonhosted.org pyvirtualdisplay

いつも使うなら、~/.pip/pip.confに下記と書き込めばいいらしい。

[global]
trusted-host = pypi.python.org
               pypi.org
               files.pythonhosted.org

いつものタフガイStackoverflow

stackoverflow.com

<Python> OSをチェックする。

土台のOSをチェックする。

In [5]: import platform

In [6]: platform.system()
Out[6]: 'Windows'

In [7]: os.name
Out[7]: 'nt'

マニュアル。
16.14. platform — 実行中プラットフォームの固有情報を参照する — Python 3.6.5 ドキュメント