
さて、コマンド プロンプトで一体何が起こっているのか、まったくわかりません。プロンプト ウィンドウを最小化し、ブラウザーで IP アドレスを開き、Python 経由で簡単な HTTP サーバー コマンドを実行するスクリプトを作成しようとしているだけです。
HTTP サーバー コマンドはstart
コマンドの後に実行する必要があります。HTTP サーバーを最初に実行すると、次のコマンドが実行されないからです。
このような問題を修正するために、小さな機能を追加する古いカスタム プログラムをいくつかインストールすることさえしました.exe
が、どれも正しく動作しませんでした...
編集
""
実際に、リンクが開かない原因は、HTTP サーバーが起動する前にサイトが読み込まれるためだとわかりました。そこで、新しい質問です。コマンドが機能しないように、コマンドhttp.server
の前に自分のコマンドを実行するにはどうすればよいですstart
か (HTTP サーバー コマンドの後にコマンドを実行しても機能しません。それ以降のコマンドは実行されないためです)。
再度編集
Anaksunaman さん、回答していただきありがとうございました。コマンドの最終結果は次のとおりです: (RunHTTPServer.bat):
@echo Off
start "" /min python -m http.server 8000 -b 127.0.0.1
sleep 1
start http://127.0.0.1:8000/
http.server を使用して Localhost:8000 に接続しようとすると、接続に失敗したというメッセージが表示されることがあるため、--bind を追加して 127.0.0.1 にバインドしました。
または、-b/--bind を削除して、その開始フィールドに個人アドレスを入力するだけです。
答え1
両方の呼び出しでコマンドを活用できますstart
。たとえば、Windows でバッチ ファイルを使用する場合:
@echo Off
@rem Start two separate processes via the Windows "start" command.
@rem The second command to open the browser will not be blocked.
@rem start the Python HTTP server with a minimized command window ("/min").
start "" /min python -m http.server 8000 --bind 127.0.0.1
@rem Give the HTTP server a second to start (optional).
sleep 1
@rem Open Firefox to the Python HTTP server instance.
start "" firefox http://localhost:8000
または、Pythonでほぼ同じコマンドを次のように使用することもできます。サブプロセスモジュール:
#!/Programs/Python37/python
# Start two separate processes via the Windows "start" command.
# The second command to open the browser will not be blocked.
import sys
import subprocess
import time
# "/min" (below) minimizes the spawned command window (Windows).
try:
subprocess.run('cmd /c start "" /min python -m http.server 8000 --bind 127.0.0.1')
# subprocess.run('cmd /c start "" /min python http-server.py')
# Wait for our server to start (optional)
time.sleep(1)
# Open our browser
subprocess.run('cmd /c start firefox http://localhost:8000')
except Exception as err:
print('')
print(err)
sys.exit()
ちなみに、以下のコメントで正しく指摘されているように、コマンドfirefox
でブラウザ名 (例 )を省略してstart
、Windows のデフォルトのブラウザ (つまりstart "" http://localhost:8000
またはstart http://localhost:8000
) で Web サイトを開くこともできます。