dak ブログ

python、rubyなどのプログラミング、MySQL、サーバーの設定などの備忘録。レゴの写真も。

python で Google Cloud Storage 上のデータをダウンロードする方法

2020-08-29 17:16:59 | python
python で Google Cloud Storage 上のデータをダウンロードする方法のメモ。

まず、pip install で Google Cloud Storage のライブラリをインストールします。
pip install google-cloud-storage


以下、Google Cloud Storage 上のデータを文字列に格納する方法です。
インメモリのバイトストリームの io.BytesIO オブジェクトにデータを保存し、
そこからバイナリデータを読み込んで文字列として取得します。
import sys
import io
import json
from google.cloud import storage

path = 'gs://~'
client = storage.Client()

buf = io.BytesIO()
client.download_blob_to_file(path, buf)
str = buf.getvalue().decode('utf-8')
buf.close()

print(str)


mysqlのテーブル、カラム名の一覧を調べる方法

2020-08-23 14:15:26 | mysql
mysqlのテーブル、カラム名の一覧を調べる方法のメモ。

mysql のカラム情報は information_schme DB の columns テーブルに記録されています。
mysql> show fields from columns;
+--------------------------+---------------------+------+-----+---------+-------+
| Field                    | Type                | Null | Key | Default | Extra |
+--------------------------+---------------------+------+-----+---------+-------+
| TABLE_CATALOG            | varchar(512)        | YES  |     | NULL    |       |
| TABLE_SCHEMA             | varchar(64)         | NO   |     |         |       |
| TABLE_NAME               | varchar(64)         | NO   |     |         |       |
| COLUMN_NAME              | varchar(64)         | NO   |     |         |       |
| ORDINAL_POSITION         | bigint(21) unsigned | NO   |     | 0       |       |
| COLUMN_DEFAULT           | longtext            | YES  |     | NULL    |       |
| IS_NULLABLE              | varchar(3)          | NO   |     |         |       |
| DATA_TYPE                | varchar(64)         | NO   |     |         |       |
| CHARACTER_MAXIMUM_LENGTH | bigint(21) unsigned | YES  |     | NULL    |       |
| CHARACTER_OCTET_LENGTH   | bigint(21) unsigned | YES  |     | NULL    |       |
| NUMERIC_PRECISION        | bigint(21) unsigned | YES  |     | NULL    |       |
| NUMERIC_SCALE            | bigint(21) unsigned | YES  |     | NULL    |       |
| CHARACTER_SET_NAME       | varchar(32)         | YES  |     | NULL    |       |
| COLLATION_NAME           | varchar(32)         | YES  |     | NULL    |       |
| COLUMN_TYPE              | longtext            | NO   |     | NULL    |       |
| COLUMN_KEY               | varchar(3)          | NO   |     |         |       |
| EXTRA                    | varchar(27)         | NO   |     |         |       |
| PRIVILEGES               | varchar(80)         | NO   |     |         |       |
| COLUMN_COMMENT           | varchar(255)        | NO   |     |         |       |
+--------------------------+---------------------+------+-----+---------+-------+

以下のテーブルを作成します。
drop table if exists test1;
create table test1 (
       col1  varchar(256),
       col2  varchar(256)
);

drop table if exists test2;
create table test2 (
       col1  varchar(256),
       col2  varchar(256)
);

上記のテーブル情報を確認できます。
mysql> select table_name, column_name from information_schema.columns
    -> where table_schema = '{DB名}';
+------------+-------------+
| table_name | column_name |
+------------+-------------+
| test1      | col1        |
| test1      | col2        |
| test2      | col1        |
| test2      | col2        |
+------------+-------------+




python で subprocess を使ってコマンドを実行する方法

2020-08-15 20:44:15 | python
python で subprocess を使ってコマンドを実行する方法のメモ。

■実行するコマンドと引数をリストで指定し、コマンドの実行結果を stdout、stderr に出力する場合:
import subprocess

res = subprocess.run(['ls', '-a'])
print(res)

実行すると、ls -a の結果が stdout に出力されます。
.  ..  test1.py
CompletedProcess(args=['ls', '-a'], returncode=0)


■実行するコマンドと引数を文字列で指定し、コマンドの実行結果を stdout、stderr に出力する場合:
res = subprocess.run('ls -a', shell=True)
print(res)

実行すると、ls -a の結果が stdout に出力されます。
返却値の args が 'ls -a' という文字列になっています。
.  ..  test1.py
CompletedProcess(args='ls -a', returncode=0)


■コマンドの実行結果をプログラム側で取得する場合:
res = subprocess.run('ls -a', shell=True,
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(res)
print(res.stdout)
print(res.stderr)

実行すると、res.stdout、res.stderr に実行結果がバイト列で格納されます。
CompletedProcess(args='ls -a', returncode=0, stdout=b'.\n..\ntest1.py\n', stderr=b'')
b'.\n..\ntest1.py\n'
b''

バイト列ではなく、文字列として取得する場合には、encoding を指定します。
res = subprocess.run('ls -a', shell=True,
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                     encoding='utf-8')
print(res)
print(res.stdout)
print(res.stderr)

出力結果が文字列となっていることがわかります。
CompletedProcess(args='ls -a', returncode=0, stdout='.\n..\ntest1.py\n', stderr='')
.
..
test1.py




wordファイル(.docx)から本文テキストを抽出する方法

2020-08-12 22:31:43 | python
wordファイル(.docx)から本文テキストを抽出する方法のメモ。

docx ファイルは zip ファイルになっているため、zip ファイルとして読み込み、
word/document.xml から本文を抽出します。
以下のプログラムでは、ルビを除去するため、<w:rt>タグを削除しています。
import sys
import json
import re
import lxml.etree
import zipfile


def extract_text(node):
    text = lxml.etree.tostring(node, encoding='utf-8').decode('utf-8')
    text = re.sub('<w:rt>.*?</w:rt>', '', text)
    text = re.sub('<.*?>', '', text)

    return text


def run():
    xmlns = {'w':'http://schemas.openxmlformats.org/wordprocessingml/2006/main'\
}

    zip = zipfile.ZipFile(sys.argv[1])
    if zip is None:
        sys.stderr.write('error: failed to open %s' % (sys.argv[0]))
        return 1

    xmlstr = zip.read('word/document.xml')
    dom = lxml.etree.fromstring(xmlstr)

    text_nodes = dom.xpath('//w:p', namespaces=xmlns)
    for text_node in text_nodes:
        text = extract_text(text_node)
        if text == '':
            continue

        print(text)

    zip.close()

    return 0


if __name__ == '__main__':
    res = run()
    exit(res)