LoginSignup
0
1

More than 5 years have passed since last update.

netifacesを使ったCONFIGにIPアドレスを書き込むコード

Last updated at Posted at 2017-06-26

Python3で書く、IPアドレスをCONFIGファイルに書き込むプログラム。
ターミナル上に以下のコードを入力する。
pip3 install netifaces

import netifaces
def main():
    i = 0
    f = open('CONFIG', 'w')
    str = "import multiprocessing" +  '\n'
    f.write(str)
    for iface_name in netifaces.interfaces():
        iface_data = netifaces.ifaddresses(iface_name)
        ip_adressList = iface_data.get(netifaces.AF_INET)
        if ip_adressList != None:
            print(ip_adressList[0]['addr'])
            ip_address = ip_adressList[0]['addr']
            str = "bind = " + "\"" +ip_address + "\"" + '\n'
            f.write(str)
    str = "workers = multiprocessing.cpu_count() * 2 + 1"
    f.write(str)
    f.close()

main()

訂正後

import netifaces

def main():
    f = open('CONFIG', 'w')
    f.write("import multiprocessing" +  '\n')
    for iface_name in netifaces.interfaces():
        iface_data = netifaces.ifaddresses(iface_name)
        ip_adressList = iface_data.get(netifaces.AF_INET)
        if ip_adressList != None:
            ip_address = ip_adressList[0]['addr']
            text = 'bind = "%s"\n' % ip_address
            f.write(text)
    f.write("workers = multiprocessing.cpu_count() * 2 + 1")
    f.close()

main()

結果、CONFIGファイルに以下のコードが書き込まれる。

import multiprocessing
bind = "127.0.0.1" #ローカルIPアドレス
bind = "◯◯◯.◯◯.◯◯.◯◯◯" #IPアドレス
workers = multiprocessing.cpu_count() * 2 + 1
0
1
2

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
1