signal.alarm not triggering exception on time

2024/10/4 11:16:07

I've slightly modified the signal example from the official docs (bottom of page).

I'm calling sleep 10 but I would like an alarm to be raised after 1 second. When I run the following snippet it takes way more than 1 second to trigger the exception (I think it runs the full 10 seconds).

import signal, osdef handler(signum, frame):print 'Interrupted', signumraise IOError("Should after 1 second")signal.signal(signal.SIGALRM, handler)
signal.alarm(1)os.system('sleep 10')signal.alarm(0)

How can I be sure to terminate a function after a timeout in a single-threaded application?

Answer

From the docs:

A Python signal handler does not get executed inside the low-level (C)signal handler. Instead, the low-level signal handler sets a flagwhich tells the virtual machine to execute the corresponding Pythonsignal handler at a later point(for example at the next bytecodeinstruction).

Therefore, a signal such as that generated by signal.alarm() can't terminate a function after a timeout in some cases. Either the function should cooperate by allowing other Python code to run (e.g., by calling PyErr_CheckSignals() periodically in C code) or you should use a separate process, to terminate the function in time.

Your case can be fixed if you use subprocess.check_call('sleep 10'.split()) instead of os.system('sleep 10').

https://en.xdnf.cn/q/70612.html

Related Q&A

Execute Python (selenium) script in crontab

I have read most of the python/cron here in stackoverflow and yet couldnt make my script run. I understood that I need to run my script through shell (using zsh & ipython by the way), but really I …

Get post data from ajax post request in python file

Im trying to post some data with an ajax post request and execute a python file, retrieving the data in the python file, and return a result.I have the following ajax code$(function () {$("#upload…

How to implement maclaurin series in keras?

I am trying to implement expandable CNN by using maclaurin series. The basic idea is the first input node can be decomposed into multiple nodes with different orders and coefficients. Decomposing singl…

Rowwise min() and max() fails for column with NaNs

I am trying to take the rowwise max (and min) of two columns containing datesfrom datetime import date import pandas as pd import numpy as np df = pd.DataFrame({date_a : [date(2015, 1, 1), date(2012…

Convert column suffixes from pandas join into a MultiIndex

I have two pandas DataFrames with (not necessarily) identical index and column names. >>> df_L = pd.DataFrame({X: [1, 3], Y: [5, 7]})>>> df_R = pd.DataFrame({X: [2, 4], Y: [6, 8]})I c…

sys-package-mgr*: cant create package cache dir when run python script with Jython

I want to run Python script with Jython. the result show correctly, but at the same time there is an warning message, "sys-package-mgr*: cant create package cache dir"How could I solve this p…

Python WWW macro

i need something like iMacros for Python. It would be great to have something like that:browse_to(www.google.com) type_in_input(search, query) click_button(search) list = get_all(<p>)Do you know …

Django custom context_processors in render_to_string method

Im building a function to send email and I need to use a context_processor variable inside the HTML template of the email, but this dont work.Example:def send_email(plain_body_template_name, html_body_…

Using string as variable name

Is there any way for me to use a string to call a method of a class? Heres an example that will hopefully explain better (using the way I think it should be):class helloworld():def world(self):print &…

How to sum all amounts by date in pandas dataframe?

I have dataframe with fields last_payout and amount. I need to sum all amount for each month and plot the output. df[[last_payout,amount]].dtypeslast_payout datetime64[ns] amount float64 d…