
好吧,我對命令提示字元中到底發生了什麼感到完全困惑。我只是想編寫一個腳本來最小化提示窗口,在瀏覽器中打開一個 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/
我新增了 --bind 將其綁定到 127.0.0.1,因為有時在使用 http.server 並嘗試連接到 Localhost:8000 時,它會說連接失敗...
這樣,或刪除 -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
在命令中省略瀏覽器名稱(例如 ) ,以簡單地在 Windows 的預設瀏覽器(即甚至只是)start
中開啟網站。start "" http://localhost:8000
start http://localhost:8000