def add(x, y): return x + y print(f"{add(5,7)=}") # result: add(5,7)=12
記事:
記事:
記事:
python -c 'import sys;import pprint;pprint.pprint(sys.path)'
str.rstrip('\n')
python3 -m http.server 8080 &
python2 -m SimpleHTTPServer 8080 &
curl localhost:8080 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"><html> <title>Directory listing for /</title> ...
pkill -u $USER python
python -c 'print("%d %s" % (1, "2str"))' 1 2str # python2.6〜 python -c 'print("{0} {1}".format(1, "2str"))' 1 2str python -c 'print("{var1} {var2}".format(var1=1, var2="2str"))' 1 2str
# python 3.6〜 python3 -c 'var1="1";var2="2str";print(f"{var1} {var2}");' 1 2str
記事:
他言語のように構文チェック用のコマンドラインオプションは無いようだ。
pip install autopep8
pip install pylint astroid --pre -U pylint --generate-rcfile > ~/.pylintrc
python -m source.py
try: f = open('sample.txt', 'r') except Exception, e: import traceback traceback.print_exc()
./exception.py Traceback (most recent call last): File "./exception.py", line 13, in <module> f = open('sample.txt', 'r') IOError: [Errno 2] No such file or directory: 'sample.txt'
import requests import requests.packages.urllib3 requests.packages.urllib3.disable_warnings()
cat example.yml dict1: foo: email: foo@example.com bar: email: bar@example.com ./example-yaml.py < example.yml - email: foo@example.com name: foo - email: bar@example.com name: bar
pythonデフォルトのデバッガはpdbだが、前後のソースコードが表示されないため、分かりにくい。
pudbはMain, Variables, Stack, Breakpoints画面に分割されるため操作しやすい。
sudo pip install pudb
pudb example.py
コマンド | 説明 |
? | ヘルプ |
q | 終了 |
n | ステップオーバー |
s | ステップイン |
r | リターン |
b | ブレークポイント |
python -m pdb example.py
File "/usr/local/lib/python2.7/httplib.py", line 924, in putheader str = '%s: %s' % (header, '\r\n\t'.join(values)) TypeError: sequence item 0: expected string, int found
wget http://httplib2.googlecode.com/files/httplib2-0.8.zip unzip httplib2-0.8.zip cd httplib2-0.8/ sudo python setup.py install
python -c "help('modules')"
pprint()では文字列、数値、リストといった特定のオブジェクトしかダンプしてくれない。
PHPのvar_dumpはクラス内部の変数もダンプしてくれて便利だったので、似たようなものがあった。
sudo pip install var_dump
vim test.py ---- # -*- coding:utf-8 -*- import sys from pprint import pprint from var_dump import var_dump class node(object): def __init__(self, name, contents=[]): self.name = name self.contents = contents[:] x = [node("node-1")] print("pprint: ") pprint(x) print("var_dump: ") var_dump(x) ---- python test.py pprint: [<__main__.node object at 0x7f15f9723850>] var_dump: [{'__type__': '<node #0x7f15f9723850>', 'contents': [], 'name': 'node-1'}]
import socket import binascii def wol(macs, ip='<broadcast>', port=9): """ wake on lan """ macs = macs.split(',') s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) for mac in macs: for sep in ':-': if sep in mac: mac = ''.join([x.rjust(2, '0') for x in mac.split(sep)]) break mac = mac.rjust(12, '0') p = '\xff' * 6 + binascii.unhexlify(mac) * 16 s.sendto(p, (ip, port)) s.close() wol(macs='11-22-33-44-55-66,77-88-99-AA-BB-CC') # 文字列 wol(macs=['11-22-33-44-55-66','77-88-99-AA-BB-CC']) # 配列
print isinstance("test", str) # True print isinstance(10, int) # True
sudo pip install ping vim ping.py ---- import ping print ping.verbose_ping("localhost") ---- sudo python ping.py ping localhost with ... get ping in 0.0730ms ping localhost with ... get ping in 0.0420ms ping localhost with ... get ping in 0.0379ms ping localhost with ... get ping in 0.0379ms
import socket def is_port_open(ip, port): try: s = socket.socket(socket.AF_INET, socket.SOCK_STREAM,0) s.settimeout(1) s.connect((ip, int(port))) s.close() return True except Exception, e: return False print is_port_open('localhost', 22) # True
分岐して代入処理が1行で書ける
if 10 % 2 == 0: var1 = 'even' else: var1 = 'odd' print var1 # even
var1 = 'even' if 10 % 2 == 0 else 'odd' print var1 # even
# -*- coding: utf8 -*- import os import hashlib import base64 def slappasswd(password, password_scheme, salt=os.urandom(4)): hash = False if password_scheme == "{SSHA}": ctx = hashlib.sha1() ctx.update( password ) ctx.update( salt ) hash = "{SSHA}" + base64.b64encode( ctx.digest() + salt ) elif password_scheme == "{SHA}": ctx = hashlib.sha1() ctx.update( password ) hash = "{SHA}" + base64.b64encode( ctx.digest() ) return hash print slappasswd('secret', '{SSHA}') # {SSHA}QYkKRfdg3uEIajHpiyYXxUJSBqaZTRod print slappasswd('secret', '{SHA}') # {SHA}5en6G6MezRroT3XKqkdPOmY/BfQ=
var1="foo" var2="bar" str=r"""var1={var1} var2={var2} {{str}}""".format(**vars()) print str
var1=foo var2=bar {str}
import tempfile import shutil temp_dir=tempfile.mkdtemp() print("temp_dir: %s" % temp_dir) # temp_dir: /tmp/tmpMCBIX7 shutil.rmtree(temp_dir)
# -*- coding: utf8 -*- import re s = """\ 200 /test.html 404 /foo/bar.html 200 /404.html""" print re.findall(r'^404 (.+)', s, re.MULTILINE) # ['/foo/bar.html']
# -*- coding: utf8 -*- import re s = """\ 200 /test.html 404 /foo/bar.html 200 /404.html""" print re.compile(r'^404.+[\r\n]+', re.MULTILINE).sub('', s) # 200 /test.html # 200 /404.html
# -*- coding: utf8 -*- import tempfile if __name__ == '__main__': fp=tempfile.NamedTemporaryFile(delete=True) print("%s" % (fp.name)) # /tmp/tmpEOKEJF fp.write("Hello World!") fp.close() # vim: ts=4 sw=4 expandtab
# -*- coding: utf8 -*- import tempfile import shutil temp_dir=tempfile.mkdtemp() print("temp_dir: %s" % temp_dir) # temp_dir: /tmp/tmpMCBIX7 shutil.rmtree(temp_dir) # vim: ts=4 sw=4 expandtab
message = """ default message """[1:-1] print(message)
# -*- coding: utf8 -*- import textwrap - if __name__ == '__main__': print '''\ default message''' print '''\ indent message''' print textwrap.dedent('''\ textwrap.dedent message''') # vim: ts=4 sw=4 expandtab
python test.py default message indent message textwrap.dedent message
# -*- coding: utf8 -*- # sudo pip install python-dateutil from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta start_date = datetime.strptime('20130930', '%Y%m%d') end_date = datetime.strptime('20131002', '%Y%m%d') # date span for dt in range((end_date - start_date).days + 1): print start_date + timedelta(dt) # 2013-09-30 00:00:00 # 2013-10-01 00:00:00 # 2013-10-02 00:00:00 # month span print start_date while(start_date.year != end_date.year or start_date.month != end_date.month): start_date = start_date + relativedelta(months=1) print start_date # 2013-09-30 00:00:00 # 2013-10-30 00:00:00
sudo pip install pytz
from datetime import datetime, tzinfo import pytz # デフォルトはtimezoneが無い print datetime.now().strftime('%Y-%m-%d %H:%M:%S %Z') # 2013-10-22 16:37:01 # UTC print datetime.now(pytz.timezone('UTC')).strftime('%Y-%m-%d %H:%M:%S %Z') # 2013-10-22 07:37:53 UTC # GMT print datetime.now(pytz.timezone('GMT')).strftime('%Y-%m-%d %H:%M:%S %Z') # 2013-10-22 07:37:53 GMT # JST print datetime.now(pytz.timezone('Asia/Tokyo')).strftime('%Y-%m-%d %H:%M:%S %Z') # 2013-10-22 16:38:30 JST # UTCからJSTへ変換 date_utc=datetime.now(pytz.timezone('UTC')) print date_utc.strftime('%Y-%m-%d %H:%M:%S %Z') # 2013-10-22 08:01:06 UTC print date_utc.replace(tzinfo=pytz.timezone('UTC')).astimezone(pytz.timezone('Asia/Tokyo')).strftime('%Y-%m-%d %H:%M:%S %Z') # 2013-10-22 17:01:06 JST # 日付文字列からdatetimeへ変換 date_str="22/Oct/2013:17:19:41 +0900" date_jst=datetime.strptime(date_str, '%d/%b/%Y:%H:%M:%S +0900') # %zが使えなかった(Python 2.6.6, 2.7) print date_jst.strftime('%Y-%m-%d %H:%M:%S %Z') # 2013-10-22 17:19:41
import sys from pprint import pprint argv=sys.argv argc=len(sys.argv) pprint(argc) pprint(argv)
python test.py foo bar 3 ['test.py', 'foo', 'bar']
from logging import getLogger, StreamHandler, Formatter, DEBUG logger = getLogger(__name__) formatter = Formatter('%(asctime)s %(levelname)-8s %(message)s') handler = StreamHandler() handler.setLevel(DEBUG) handler.setFormatter(formatter) logger.setLevel(DEBUG) logger.addHandler(handler) logger.debug("debug") logger.info("info") logger.warning("warning") logger.error("error") logger.critical("critical")
2017-08-01 14:56:32,251 DEBUG debug 2017-08-01 14:56:32,251 INFO info 2017-08-01 14:56:32,251 WARNING warning 2017-08-01 14:56:32,252 ERROR error 2017-08-01 14:56:32,252 CRITICAL critical
# -*- coding: utf-8 -*-
d = {'hoge': 100, 'foo':200, 'bar':300} if d.has_key('hoge'): print 'hoge found!'
if hasattr('env', 'hoge'): print(env.hoge)
urllib.FancyURLopenerをオーバーライドしてID/PASSを返してやれば良い。
import urllib class MyURLopener(urllib.FancyURLopener): def prompt_user_passwd(self, host, realm): if host == 'ホスト名': return ('ID', 'Password') def execute(hdf, args, env): opener = MyURLopener({}) f = opener.open('https://svn.example.com/projects/ppc/wiki/FctlPpc/mysql') print f.read() f.close() execute(1,2,3)
記事: