peer
peer

Reputation: 162

Tkinter Window Freezes after Running a Server from Script

I am making a program that creates an separate python web server, the server being:

import os, sys
from http.server import HTTPServer, CGIHTTPRequestHandler

webdir = '.'
port = 8000
print('Server Now Running')
os.chdir(webdir)
srvraddr = (('' , port))
srvrobj = HTTPServer(srvraddr, CGIHTTPRequestHandler)
srvrobj.serve_forever()

and then original program runs that server from command line:

def runServer(self):
    os.system('Webserver.py')

All of this is done with buttons in a Tkinter window. When this function is called, the Tkinter window freezes and the next button cannot be pressed (one which would pull up a local html file in Safari, through the server).

I've looked around and it looks like I might need threading or something...

I have am left clueless as to how I would go about this. Can provide more of my original program if necessary (it's a bit clunky).

I'm looking for a simple solution or maybe a specific reference to get me heading in the right direction.

Very new (3 months) to Python, so please keep this in mind.

Upvotes: 1

Views: 677

Answers (2)

furas
furas

Reputation: 142794

Use subprocess

import subprocess

s = subprocess.Popen(['Webserver.py'])

or maybe it will need python to start script

s = subprocess.Popen(['python', 'Webserver.py'])

or you can run

s = subprocess.Popen(['python3', '-m', 'http.server', '--cgi', '8000'])

and later you can stop process

s.kill()

  • Popen (without argument shell=True) expects argument as list
  • after you close program subprocess still works so you have to kill them before you close program.

Upvotes: 2

Matthias Gilch
Matthias Gilch

Reputation: 306

Since the exit code of the called program is the return value of the function os.system, the program is blocked until the called program exited.

Try using the non-blocking subprocess.Popen instead.

Upvotes: 1

Related Questions