Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
377 views
in Technique[技术] by (71.8m points)

python - How to resume program (or exit) after opening webbrowser?

I'm making a small Python program, which calls the webbrowser module to open a URL. Opening the URL works wonderfully.

My problem is that once this line of code is reached, the problem is unresponsive. How do I get the program to proceed past this line of code and continue to execute? Below the problematic line is the problematic line, in context:

if viewinbrowser == "y":
    print "I can definitely do that. Loading URL now!"
    webbrowser.open_new(url)
    print "Exiting..."
    sys.exit()

The program does not get as far as executing the print "Exiting...", which I added because I noticed the program wasn't leaving the if statement for some reason.

I am running this program from the command line, in case that's important. Edit: I am running on Kubuntu 9.04 i386, using KDE 4.3 via backports. I use Firefox 3.5 as my default browser, declared in the System Settings for KDE, and it is called correctly by the program. (At least, a new tab opens up in Firefox with the desired URL—I believe that is the desired functionality.) /Edit

Also, I assume this problem would happen with pretty much any external call, but I'm very new to Python and don't know the terminology to search for on this site. (Searching for "python webbrowser" didn't yield anything helpful.) So, I apologize if it's already been discussed under a different heading!

Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This looks like it depends on which platform you're running on.

  • MacOSX - returns True immediately and opens up browser window. Presumably your desired behavior.
  • Linux (no X) - Open up links textmode browser. Once this is closed, returns True.
  • Linux (with X) - Opens up Konquerer (in my case). Returns True immediately. Your desired behavior.

I'm guessing you're on Windows, which, as another commentor mentioned doesn't have fork. I'm also guessing that the webbrowser module uses fork internally, which is why it's not working for you on Windows. If so, then using the threading module to create a new thread that opens the webbrowser might be the easiest solution:

>>> import webbrowser
>>> import threading
>>> x=lambda: webbrowser.open_new('http://scompt.com')
>>> t=threading.Thread(target=x)
>>> t.start()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...