LoginSignup
1
1

More than 1 year has passed since last update.

python 備忘録

Last updated at Posted at 2022-04-14

python バージョン確認

python -V

pip 一覧

pip freeze
pip list

警告が出るとき

WARNING: Running pip install with root privileges is generally not a good idea. Try `pip3 install --user` instead.

パッケージをグローバルインストールすることでパッケージがコンフリクトするリスクがあることの警告。
→ pip installにはグローバルインストール(デフォルト)と--userをオプションに付けるローカルインストールが存在する。
そのまま放っておけばインストールが開始される。

コメントアウト

# 1行コメントアウト シャープ
'''
複数行
コメントアウト
シングルクォーテーション3つ
'''

pythonファイル実行

cd /設置場所
./ファイル名.py

関数の呼び出し

説明 備考
python3 -c "import ファイル名; ファイル名.関数名()" ファイル名に拡張子(.py)は不要
パラメータはシングルクォーテーションで囲うこと

python3 -c "import PythonFileName; PythonFileName.DefName('para1','para2')"

関数定義

def_test.py
def sample():
  print "def_test"
sample()

注意 NameError

関数を定義前に呼び出すとNameErrorが発生する

NameError_test.py
# NameError: name 'sample' is not defined
sample()
def sample():
  print "def_test"

ダンダー __name__

説明 __name__ の中身 ファイル名
呼び出す側 __main__ sample01.py
呼び出される側 sample02 sample02.py
python sample01.py
sample01.py
import sample02
def main():
	sample02.function()
if __name__ == "__main__":
	print("sample01 __name__ → " + __name__ )
    #sample01 __name__ → __main__
	main()
sample02.py
def function():
    print("sample02 __name__ → " + __name__ )
    #sample02 __name__ → sample02

文字列

長さ

w="こんにちは"
print(len(w))

#結果:5

切り取り

0 1 2 3 4 5
-6 -5 -4 -3 -2 -1
w="こんにちは"
print(w[0])
print(w[1:2])
print(w[-3:])

#結果
#こ
#んに
#ちわ。

if

if 条件式1:
    print("条件式1が真の時に実行する文")
elif 条件式2:
    print("条件式1が偽で条件式2が真の時に実行する文")
elif 条件式3:
    #何もしない場合は「pass」がないと「IndentationError」が発生する
    pass
else:
    print("すべての条件式が偽のときに実行する文")
比較 記述 備考
完全一致(等価) ==, !=
部分一致 in, not in
前方一致・後方一致(先頭・末尾) startswith(), endswith()
文字列の大小関係(順番) <, <=, >, >=
正規表現パターンにマッチ re.search(), re.fullmatch() print(re.search('a', 'a-b-c'))※

※ trueなら「re.Match object; span=(x, x), match='xxx'」 ,falseなら「None」が返されるが、if文でも使用可能

参考文献

for

回数指定

for i in range(3):
    print("test:" + str(i))
# test:0 test:1 test:2

words = ['a', 'b', 'c']
for w in words:
    print ("test:" + w)
# test:a test:b test:c

TypeError

string型 と int 型 を連結すると TypeErrorが発生する
→ str(i) とすることでキャストできる。

print("test" + i)

replace

str = 'aaa ddd ccc'
print(str.replace('ddd', 'bbb'))
# aaa bbb ccc

正規表現で置換

str = 'testStr'
print(re.sub('test*','replaceSample', str))
#replaceSample

re.sub('正規表現','置換文字',適用する文章)

split

str = 'aaa|ddd|ccc'
print(str.split('|'))
#['aaa', 'ddd', 'ccc']

print(str.split('|')[0])
#aaa

try catch

例外全て

def sample():
    try:
        raise Exception
    except:
        traceback.print_exc()
        print('Error')

特定の例外+例外全て

def sample():
    try:
        #raise Exception
        raise ValueError("error!")

    except ValueError as e:
        print('ValueError:', e)
    except:
        traceback.print_exc()
        print('Error')

ポイント

項目 説明 備考
traceback.print_exc() エラー時のスタックトレースを表示する

ファイル読み込み

#closeは自動で処理される
with open("book.txt", "r") as fileread:
  print(fileread.read())

ファイルの書き込み w:新規作成&上書き

with open('ファイル名','w')as f
    f.write('文字列')

subprocessの戻り値を加工してファイル書き込み

with open('myfile.txt', 'w')as f:
    cp = subprocess.run(['free'], encoding='utf-8', stdout=subprocess.PIPE)
    #freeコマンドの結果をcsv形式に変換
    cp.stdout = (re.sub(' +',',',cp.stdout))
    print(cp.stdout)
    f.write(cp.stdout)

正規表現の置換

re.sub('正規表現','置換文字',適用する文章)

subprocessの結果をファイルに書き込み

import subprocess

with open('out.txt', 'w') as fp:
  subprocess.run(['ls', '-1'], stdout=fp)

詳細

シングルトン実装

    singleton = None
    def __new__( cls, *args, **kwargs ):
        #1回目のクラス生成(クラスインスタンスが無ければ作成する)
        if cls.singleton == None:
            cls.singleton = super().__new__( cls )
        #クラスのインスタンスを返す
        return cls.singleton

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1