Unable to close Asynchronous Web.py Web Server

Referring to this example, I am curious why it's not possible to terminate this program using Ctrl+C:

#!/usr/bin/env python
import web
import threading
class MyWebserver(threading.Thread):
   def run (self):
      urls = ('/', 'MyWebserver')
      app = web.application(urls, globals())
      app.run()

   def POST (self):
      pass

if __name__ == '__main__':
   MyWebserver().start()

Answer №1

Start the thread with this code snippet:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import web
import threading

from time import sleep

class MyWebserver(threading.Thread):
    def run(self):
        urls = ('/', 'MyWebserver')
        app = web.application(urls, globals())
        app.run()

if __name__ == '__main__':
    t = MyWebserver()
    t.daemon = True
    t.start()
    while True:
        sleep(100)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is Python BeautifulSoup's findAll function not returning all the elements in the web page

I am attempting to retrieve information from the following URL . Displayed below is the code I have developed. import requests from bs4 import BeautifulSoup url_str = 'https://99airdrops.com/page/1/' page = requests.get(url_str, headers={&apo ...

What is the process for recreating a thread with different parameters?

I am working on a multithreading program that sends emails to my clients. However, I am facing some issues with the threads in my code - they only close the window of Firefox and do not continue the desired actions. I am looking to create an algorithm wher ...

Is it possible that Selenium's get_property function returns None?

I'm having trouble getting properties from elements on webpages, and I can't figure out what the issue is. To illustrate my problem, I've created a simple test case: from selenium import webdriver URL = "https://stackoverflow.com/tour& ...

Accelerate the process of converting numerous JSON files into a Pandas dataframe within a for-loop

Here is a function I've created: def json_to_pickle(json_path=REVIEWS_JSON_DIR, pickle_path=REVIEWS_PICKLE_DIR, force_update=False): '''Generate a pickled dataframe from specified JSON files.&ap ...

What are the steps to correctly set up PyGObject on macOS?

I am looking to run some basic examples and write code using GStreamer with its Python bindings. I need help installing the necessary packages to get started. Check out this example: import gi gi.require_version('Gst', '1.0') from g ...

Combining 2 datasets with highlighted discrepancies

Looking to merge two simple dataframes together? If a cell value is present in df_history but not in df_now, you want it added with a prefix. Check out the example image below: https://i.stack.imgur.com/eZFqV.png My approach so far: Convert both datafra ...

Regex101 is successful in processing Regular Expression, whereas Jupyter notebook encounters difficulties with it

import re with open('names.txt') as f: data = f.readlines() twitter_pattern = re.compile(r"\s{1}[@]\w+") twitter_match = twitter_pattern.findall(str(data)) print(twitter_match) names.txt contains a list of full names, p ...

What is the process of logging in pytest while utilizing the AWS Chalice framework?

Is there a way to print logs in pytest using the AWS Chalice framework? The log prints everything when we use a custom logger. import logging logger = logging.getLogger() logger.setLevel(logging.DEBUG) When running tests with log-level specified (curren ...

How can recursive data be displayed in a template?

I am working with a model in Django that has a ForeignKey pointing to itself, and I need to display all the data from the database using lists and sublists: Below is my model definition: class Place(models.Model) name = models.CharField(max_length=1 ...

Having trouble grasping the concept of a GEOHAYSTACK index in pymongo? Wondering which index would provide the best performance?

I have a large document and I am looking to optimize the most queried field by adding an index. After testing all of the indexes provided by pymongo, I found that the GEOHAYSTACK index was the fastest. Here is how I added indexes to the documents: self.e ...

"Enhance your Django application with custom import and export functionality by

Currently facing an issue in Django/Python that I haven't been able to solve. I need to override "get_instance" in django-import-export.instance_loaders At the moment, I have made changes directly in this function. I realize this may not be the best ...

Insert a vertical divider to separate icons and text within a menu

I'm seeking guidance on how to implement separators between icons and text in a menu. Any suggestions would be greatly appreciated. The specific task I am looking to accomplish is: . Open a menu from a button and incorporate separators as shown in t ...

The mysterious results of the 2F1 function in the scipy module

Why does hyp2f1 from scipy return 1? Shouldn't it be something else? https://i.stack.imgur.com/iEWIr.png Below is the code I used import numpy as np from scipy import special x = np.arange(0,2,0.01) y = special.hyp2f1(-1/2, 1/2, 2, -400/(1-8/9*np.c ...

Instead of creating a new figure each time in a loop for imshow() in matplotlib, consider updating the current plot instead

I am facing a challenge where I need to save displayed images based on user input, but the issue lies in the fact that unlike plt.other_plots(), plt.imshow() does not overwrite the existing figure, rather it creates a new figure below the existing one. How ...

My Python program is receiving a "400 Bad Request" error from the Strawpoll.me API, yet the API functions properly when accessed through the terminal

I recently wrote a Python program to generate strawpolls using the API provided by strawpoll.me. You can find more information about the API here. import aiohttp import asyncio async def createPoll(): question = "Is this thing on?" options = ["Ye ...

Guide to interacting with webpage elements using Selenium and Python to trigger them based on their HTML properties

I have been struggling to locate this specific element using Python Selenium. Despite trying various methods like xpath, CSS selectors, and classes, I have not been able to find the element in question. Could anyone provide guidance on how to locate and cl ...

Choosing multiple classes using Xpath

<div class="unique"> <a class="nested" href="Another..."><img src="http://..."/></a> <p> different.... </p> <p><img src="http://....." /></p> </div> I have this interesting HTML struc ...

Choosing a BeautifulSoup tag according to attribute value

Imagine we have an HTML page with an index and some content below. Each element in the index is linked to a related section in the document. Let's say our starting point is an anchor tag with an href value of "#001". We want to search through all the ...

I'm receiving an error message stating that the file cannot be loaded due to disabled script execution on this system. Can you

Currently facing an issue while loading a python file in PyCharm. There is a warning popping up which wasn't there before. Interestingly, print('Hello') function is working fine but I am encountering difficulties in installing Django. Encoun ...

random identifier selection using selenium's xpath and css selector algorithm

Hello, I am a newcomer to using Selenium with Python. I am facing an issue where the id, xpath, and css selector contain random values each time I navigate to the page. I have tried using various methods like xpath, id, css selector, and even class name to ...