LoginSignup
0
1

More than 1 year has passed since last update.

PythonでHTML生成、WEBサーバ起動、ブラウザ参照を自動で実行

Posted at

はじめに

Pythonであるシステムに画面を組み込む話があったのだが、テスト時にシステム全体をインストールしたくなかったので、単体で画面を表示するドライバを作ってみた。

環境

  • python 3.6

ソース

こんな感じ。

import argparse
import http.server
import socketserver
import webbrowser
import threading

def main():
    PORT = 8009
    Handler = http.server.SimpleHTTPRequestHandler
    socketserver.TCPServer.allow_reuse_address = True    
    server = socketserver.TCPServer(("", PORT), Handler)
    server_thread = threading.Thread(target=server.serve_forever)    
    server_thread.daemon = True
    server_thread.start()
    print("Web server running in thread:", server_thread.name)
    webbrowser.open("http://localhost:{0}/html/test.html".format(PORT))

    import time
    from datetime import datetime
    try:
        while(True):
            time.sleep(10000)
    except KeyboardInterrupt: 
        print("closing")
        #server.shutdown()
        server.socket.close()                   
        import sys
        sys.exit()


if __name__ == "__main__":
    main()

解説

  • コマンドを実行すると、WEBサーバを立ち上げ、ブラウザを開き、プログラムの直下のhtmlフォルダの下のtest.htmlを表示する。
  • WEBサーバを立ち上げた後にブラウザを開けるよう、WEBサーバはスレッドで立ち上げている。
  • 途中でCtr-Cによりキャンセルできるようにしている。

VisualStudioのLive Serverでいいじゃんという話もあるが、これだとPythonしかない環境に配布を行うことができる。

参考

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