0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

re.subを使って複数の空白文字を任意のセパレータ文字に変換

Posted at

文字列の中の複数の空白文字(スペース)を、正規表現を使ってコンマ(,)に変換する

ユースケース

  • コマンド結果を文字列として取り込み、それを加工して使用する
  • 例:ネットワークコマンドの実行結果など
~$ ss -tu
Netid      State      Recv-Q      Send-Q           Local Address:Port              Peer Address:Port       Process
tcp        ESTAB      0           0                    127.0.0.1:59976                127.0.0.1:39839
tcp        ESTAB      0           0                    127.0.0.1:59978                127.0.0.1:39839
tcp        ESTAB      0           0                    127.0.0.1:39839                127.0.0.1:59978
tcp        ESTAB      0           0                    127.0.0.1:39839                127.0.0.1:59976
  • Linuxのコマンドは上記のような表示結果が多いので、この空白をセパレータに変更しリスト化するとデータの再利用がしやすい

コード

get_socket.py
import re
import subprocess


def get_socket():
    get_socket = subprocess.run(['ss', '-tu'],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE)
    cmd_result = get_socket.stdout.decode('utf-8')

    with open('/WorkSpace/Python/get_socket.txt', 'w') as f:
        f.write(cmd_result)

    socket_list = []

    with open('/WorkSpace/Python/get_socket.txt', 'r') as f:
        for read_line in f:
            txt_value0 = re.sub(r'\s+', ',', read_line)
            txt_value1 = txt_value0.split(',')
            socket_list.append(txt_value1)

    return socket_list

for list in get_socket():
    print(list)


if __name__ == ('__main__'):
    get_socket()

  1. subprocess.runでssコマンドを実行する
  2. コマンド結果をファイルに保存する(with open(file, 'w') as f: )
  3. ファイルから文字列を読み込む(with open(file, 'r') as f: )
  4. re.sub関数で複数空白文字 ( '\s+' ) を ( ',' ) コンマに変換する
  5. 文字列をsplit関数でセパレートに ( ',' ) を指定しリストに変換する

実行結果

python get_socket.py
['Netid', 'State', 'Recv-Q', 'Send-Q', 'Local', 'Address:Port', 'Peer', 'Address:Port', 'Process', '']
['tcp', 'ESTAB', '0', '0', '127.0.0.1:59976', '127.0.0.1:39839', '']
['tcp', 'ESTAB', '0', '0', '127.0.0.1:59978', '127.0.0.1:39839', '']
['tcp', 'ESTAB', '0', '0', '127.0.0.1:39839', '127.0.0.1:59978', '']
['tcp', 'ESTAB', '0', '150', '127.0.0.1:39839', '127.0.0.1:59976', '']
0
0
4

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?