2012-03-20 5 views
0

다음은 내 코드입니다 :webbrowser에 로컬 호스트를 열도록 브라우저를 설정하는 방법은 무엇입니까?

execfile("main.py"); 
    url = "localhost:9988"; 
    webbrowser.open_new_tab(url); 

"main.py"로컬 호스트를 시작합니다,하지만 난 스크립트를 실행할 때 그것이 로컬 호스트에 갇혀 있기 때문에 (URL)를 webbrowser.open_new_tab로 이동하지 않습니다.

localhost를 시작한 다음 선택한 브라우저 (예 : chrome/firefox)에서 localhost로 새 탭을 여는 방법이 있습니까?

답변

3

main.py는 서버이므로 요청할 때까지 종료되지 않으므로 webbrowser.open_new_tab을 호출하기 위해 새 프로세스를 만들어야합니다. subprocess.Popen, os.fork 또는 이와 유사한 것을 사용할 수 있습니다.

subprocess.Popen((sys.executable, 'main.py')) 트릭을해야합니다.

2

Popen으로 다음과 같이하십시오. 그것은 작동해야합니다. python -m SimpleHTTPServer 8000을 자신의 실행 파일로 대체해야합니다.

코드 :

import subprocess 
import webbrowser 
subprocess.Popen(['python', '-m', 'SimpleHTTPServer', '8000']) 
webbrowser.open_new_tab('localhost:8000') 

실행 :

[12:21:49] [email protected]:[/tmp]$ python 
Python 2.7.2+ (default, Oct 4 2011, 20:06:09) 
[GCC 4.6.1] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> 
>>> import subprocess 
>>> import webbrowser 
>>> 
>>> subprocess.Popen(['python', '-m', 'SimpleHTTPServer', '8000']) 
<subprocess.Popen object at 0x7f09924df210> 
>>> Serving HTTP on 0.0.0.0 port 8000 ... 

>>> webbrowser.open_new_tab('localhost:8000') 
True 
>>> localhost.localdomain - - [20/Mar/2012 12:22:29] "GET/HTTP/1.1" 200 - 
Created new window in existing browser session. 
localhost.localdomain - - [20/Mar/2012 12:22:29] code 404, message File not found 
localhost.localdomain - - [20/Mar/2012 12:22:29] "GET /favicon.ico HTTP/1.1" 404 - 

>>> 
관련 문제