python -m http.server [ポート番号]
python -m SimpleHTTPServer 8000
re.sub(正規表現, “置換する文字列”, 置換対象の文字列)
import re text = """\ 070-1234-5678 Tokyo 080-1234-5678 Chiba 090-1234-5678 Saitama """ text_mod = re.sub('^[0-9]{3}-[0-9]{4}-[0-9]{4}',"***-****-****",text, flags=re.MULTILINE) # flags=re.MULTILINEを追加 print (text_mod)
***-****-**** Tokyo ***-****-**** Chiba ***-****-**** Saitama
import re saleVal = re.compile('[0-9]{2}%') text1 = "毎月5日は全品30%オフを実施中!!!" text2 = "毎月10日は全品50%オフを実施中!!!" text_mod1 = saleVal.sub("80%",text1) text_mod2 = saleVal.sub("90%",text2) print (text_mod1) print (text_mod2)
毎月5日は全品80%オフを実施中!!! 毎月10日は全品90%オフを実施中!!!
pip install dataset
driver://user:pass@host/database
import dataset db_connect_str = 'sqlite:///C:/GitHub.Accounts.sqlite3' db = dataset.connect(db_connect_str) for account in db['Accounts']: print(account) print("id:{0},user:{1},pass:{2},mail:{3},create:{4}".format(account["Id"],account["Username"],account["Password"],account["MailAddress"],account["CreatedAt"]))
Could not find a version that satisfies the requirement xxx (from versions: ) No matching distribution found for xxx
[global] trusted-host = pypi.python.org pypi.org files.pythonhosted.org
curl https://bootstrap.pypa.io/get-pip.py | python3
export PYTHONUSERBASE=$HOME/local export PATH=$PATH:$HOME/local pip3 install --user python-language-server autopep8
pip install <PKG> --proxy=<PROXY_IP>:<PROXY_PORT>
[SSL: TLSV1_ALERT_PROTOCOL_VERSION] tlsv1 alert protocol version
$ git clone https://github.com/pyenv/pyenv.git ~/.pyenv
$ echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile $ echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile $ echo 'eval "$(pyenv init -)"' >> ~/.bash_profile $ source ~/.bash_profile
$ pyenv install 3.6.1
$ pyenv shell 2.7.1
$ pyenv local 2.7.1 # 設定したいディレクトリ直下で実行
$ pyenv global 2.7.1
$ git clone https://github.com/pyenv/pyenv-virtualenv.git ~/.pyenv/plugins/pyenv-virtualenv
$ echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.bash_profile $ source ~/.bash_profile
$ pyenv virtualenv 3.6.1 test_3.6.1
$ pyenv activate test_3.6.1
$ source deactivate
$ py -3 # ver 3を利用 $ py -2 # ver 2を利用
$ cd .pyenv/versions/2.7.12 $ mkdir bin && cd bin $ ln -s ../python.exe python
$ cd .pyenv/versions $ mv /path/to/python-3.6.2-embed-amd64 3.6.2 $ mkdir 3.6.2/bin && cd 3.6.2/bin $ ln -s ../python.exe python
user_agent = 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36' # PhantomJS本体のパス pjs_path = './phantomjs' dcap = { "phantomjs.page.settings.userAgent" : user_agent, 'marionette' : True # WebDriverにデフォルトのGhostDriverではなくFirefox後継のmarionetteを利用する(あまりわかってない) } driver = webdriver.PhantomJS(executable_path=pjs_path, desired_capabilities=dcap)
#!/usr/bin/env python import commands result = commands.getoutput("ls") print result
スクリーン描画など
def __init__(self): self.data = "A" # selfがないとstaticになる
import numpy as np x = np.array([1, 2, 3]) y = np.array([10, 20, 30]) z = np.array([3., 4., 5.]) print x + y # => [11 22 33]
[root@testserver07 ~]# yum install python-matplotlib.x86_64 --disablerepo=base ========================================================================================================= Package Arch Version Repository Size ========================================================================================================= Installing: python-matplotlib x86_64 0.91.2-1.el5.rf rpmforge 7.1 M Installing for dependencies: python-dateutil noarch 1.2-1.el5.rf rpmforge 164 k python-tz noarch 2006p-1.el5.rf rpmforge 667 k Transaction Summary =========================================================================================================
testuser@testserver07% sudo yum install -y python-numpy.x86_64 --disablerepo=base ========================================================================================================= Package Arch Version Repository Size ========================================================================================================= Installing: python-numpy x86_64 1.0.1-1.el5.rf rpmforge 2.5 M Installing for dependencies: blas x86_64 3.0-37.el5 core-2 318 k lapack x86_64 3.0-37.el5 core-2 3.5 M Transaction Summary =========================================================================================================
#!/usr/bin/python import matplotlib matplotlib.use('Agg') import pylab pylab.title("Title") pylab.figure(figsize=(10, 1.7)) pylab.plot( [ 1, 2, 3, 4,2,12] ) pylab.ylim(-1, 13) pylab.grid(True) pylab.savefig('/tmp/aaa.png') pylab.close()
import matplotlib matplotlib.use('Agg') import pylab pylab.title("Title") pylab.bar(range(1, len(DATA_LIST)+1), DATA_LIST) pylab.ylim(0, max(DATA_LIST)) pylab.grid(True) pylab.savefig("output.png") pylab.close()
#!/usr/bin/python import time print time.time() # 結果 1447294620.45
#!/usr/bin/python import time from datetime import datetime def datetime_to_epoch(d): return int(time.mktime(d.timetuple())) def epoch_to_datetime(epoch): return datetime(*time.localtime(epoch)[:6]) now = datetime.now() epoch = datetime_to_epoch(now) epoch_to_datetime(epoch)
#!/usr/bin/python import time from datetime import datetime tstr = "1980-01-01 00:00:01" tdatetime = datetime.strptime(tstr, '%Y-%m-%d %H:%M:%S')
#!/usr/bin/python import time from datetime import datetime tstr = "1980-01-01 00:00:01" tdatetime = datetime(*time.strptime(tstr, '%Y-%m-%d %H:%M:%S')[0:6])
import datetime now = datetime.datetime.now() now.strftime("%Y/%m/%d %H:%M:%S")
import time, datetime datetime.datetime.fromtimestamp(time.mktime((2008, 13, 1, 0, 0, 0, 0, 0, 0))) # <-- 2008/13/1 を 2009/1/1のdate型で返却 >> datetime.datetime(2009, 1, 1, 0, 0)
44maru@silver02% tree . |-- test1 | `-- Test1.proto `-- test2 `-- Test2.proto
#!/bin/bash # need to protoc version 2.6 OUT_PATH=./output PROTO_PATH="." PROTO_FILES="${PROTO_PATH}/test1/Test1.proto ${PROTO_PATH}/test2/Test2.proto" mkdir -p $OUT_PATH protoc -I${PROTO_PATH}/test1 -I${PROTO_PATH}/test2 --python_out=${OUT_PATH} ${PROTO_FILES}
44maru@silver02% ls ./output Test1_pb2.py Test1_pb2.pyc Test2_pb2.py Test2_pb2.pyc
#!/usr/bin/python import Test1_pb2 import cx_Oracle db_user = "TESTUSER" db_pass = db_user db_sid = "TESTDB" connection_url = "%s/%s@%s" % (db_user, db_pass, db_sid) connection = cx_Oracle.connect(connection_url) cursor = connection.cursor() try: pbReq = Test1_pb2.PBTestReq() sql = "select pb_lob_data from pb_tab where rownum = 1" for r in cursor.execute(sql): pbReq.ParseFromString(r[0].read()) print pbReq finally: cursor.close() connection.close()
from xlrd import open_workbook import sys TABLE_SHEET_NAME = "List of sheets" TABLE_TYPE_COL_INDEX = 0 TABLE_NAME_COL_INDEX = 1 TABLE_DESCRIPTION_COL_INDEX = 2 def open_table_sheet(excel_sheet_path): workbook = open_workbook(excel_sheet_path) sheet = workbook.sheet_by_name(TABLE_SHEET_NAME) return sheet def write_table_name_to(sheet): for row in range(sheet.nrows): table_type = sheet.cell(row, TABLE_TYPE_COL_INDEX).value if table_type == "Table": table_name = sheet.cell(row, TABLE_NAME_COL_INDEX).value # if table_name == '44maru': # FIXME! using xlwt sheet.write(row, TABLE_DESCRIPTION_COL_INDEX, '44maru-machi-desu') def main(): excel_sheet_path = sys.argv[1] sheet = open_table_sheet(excel_sheet_path) write_table_name_to(sheet) main()
[root@testserver07 ~]# yum install -y python-pip.noarch [root@testserver07 ~]# export http_proxy=http://192.168.22.118:3128/ [root@testserver07 ~]# export https_proxy=http://192.168.22.118:3128/ [root@testserver07 ~]# pip install jedi
[root@testserver07 ~]# export https_proxy=http://192.168.22.118:3128/ [root@testserver07 ~]# pip install pyflakes Downloading/unpacking pyflakes Downloading pyflakes-0.7.3.tar.gz Running setup.py egg_info for package pyflakes Installing collected packages: pyflakes Running setup.py install for pyflakes Installing pyflakes script to /usr/bin Successfully installed pyflakes Cleaning up...
#!/usr/bin/python """ super 44maru parser script """ import optparse class CLIParser: def __init__(self): self.parser = optparse.OptionParser() self.parser.set_description(__doc__) self.parser.set_usage('44maru.py [options] *.txt') self._setup_options() def parse_cli(self): (options, args) = self._parse_args() self._check_required_options_exist(options) return (options, args) def _parse_args(self): return self.parser.parse_args() def _setup_options(self): self.parser.add_option('-n', '--44maru', help='required option. 44maru', dest='44maru') self.parser.add_option('-c', '--christmas', help='required option. christmas', dest='christmas') self.parser.add_option('-t', '--test', help='test option yeah', dest='test') def _check_required_options_exist(self, opts): mandatories = ['44maru', 'christmas'] for m in mandatories: if not opts.__dict__[m]: self.parser.error(m + " is required option") exit(-1) if __name__ == '__main__' : parser = CLIParser() (options, args) = parser.parse_cli() print options