Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 5939443
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 22, 20262026-05-22T15:49:44+00:00 2026-05-22T15:49:44+00:00

I’ve read a lot of posts about using threads, subprocesses, etc.. A lot of

  • 0

I’ve read a lot of posts about using threads, subprocesses, etc.. A lot of it seems over complicated for what I’m trying to do…

All I want to do is stop executing a function after X amount of time has elapsed.

def big_loop(bob):
    x = bob
    start = time.time()
    while True:
        print time.time()-start

This function is an endless loop that never throws any errors or exceptions, period.
I”m not sure the difference between “commands, shells, subprocesses, threads, etc..” and this function, which is why I’m having trouble manipulating subprocesses.

I found this code here, and tried it but as you can see it keeps printing after 10 seconds have elapsed:

import time
import threading
import subprocess as sub
import time

class RunCmd(threading.Thread):
    def __init__(self, cmd, timeout):
        threading.Thread.__init__(self)
        self.cmd = cmd
        self.timeout = timeout

    def run(self):
        self.p = sub.Popen(self.cmd)
        self.p.wait()

    def Run(self):
        self.start()
        self.join(self.timeout)

        if self.is_alive():
            self.p.terminate()
            self.join()

def big_loop(bob):
    x = bob
    start = time.time()
    while True:
        print time.time()-start

RunCmd(big_loop('jimijojo'), 10).Run()  #supposed to quit after 10 seconds, but doesn't
x = raw_input('DONEEEEEEEEEEEE')

What’s a simple way this function can be killed. As you can see in my attempt above, it doesn’t terminate after 20 seconds and just keeps on going…

***OH also, I’ve read about using signal, but I”m on windows so I can’t use the alarm feature.. (python 2.7)

**assume the “infinitely running function” can’t be manipulated or changed to be non-infinite, if I could change the function, well I’d just change it to be non infinite wouldn’t I?

Here are some similar questions, which I haven’t able to port over their code to work with my simple function:
Perhaps you can?

Python: kill or terminate subprocess when timeout

signal.alarm replacement in Windows [Python]

Ok I tried an answer I received, it works.. but how can I use it if I remove the if __name__ == "__main__": statement? When I remove this statement, the loop never ends as it did before..

import multiprocessing
import Queue
import time


def infinite_loop_function(bob):
    var = bob
    start = time.time()
    while True:
        time.sleep(1)
        print time.time()-start
    print 'this statement will never print'

def wrapper(queue, bob):
    result = infinite_loop_function(bob)
    queue.put(result)
    queue.close()



#if __name__ == "__main__":

queue = multiprocessing.Queue(1) # Maximum size is 1
proc = multiprocessing.Process(target=wrapper, args=(queue, 'var'))
proc.start()

# Wait for TIMEOUT seconds
try:
    timeout = 10
    result = queue.get(True, timeout)
except Queue.Empty:
    # Deal with lack of data somehow
    result = None
finally:
    proc.terminate()

print 'running other code, now that that infinite loop has been defeated!'
print 'bla bla bla'
x = raw_input('done')
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-22T15:49:45+00:00Added an answer on May 22, 2026 at 3:49 pm

    Use the building blocks in the multiprocessing module:

    import multiprocessing
    import Queue
    
    TIMEOUT = 5
    
    def big_loop(bob):
        import time
        time.sleep(4)
        return bob*2
    
    def wrapper(queue, bob):
        result = big_loop(bob)
        queue.put(result)
        queue.close()
    
    def run_loop_with_timeout():
        bob = 21 # Whatever sensible value you need
        queue = multiprocessing.Queue(1) # Maximum size is 1
        proc = multiprocessing.Process(target=wrapper, args=(queue, bob))
        proc.start()
    
        # Wait for TIMEOUT seconds
        try:
            result = queue.get(True, TIMEOUT)
        except Queue.Empty:
            # Deal with lack of data somehow
            result = None
        finally:
            proc.terminate()
    
        # Process data here, not in try block above, otherwise your process keeps running
        print result
    
    if __name__ == "__main__":
        run_loop_with_timeout()
    

    You could also accomplish this with a Pipe/Connection pair, but I’m not familiar with their API. Change the sleep time or TIMEOUT to check the behaviour for either case.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I want to count how many characters a certain string has in PHP, but
I'm parsing an RSS feed that has an ’ in it. SimpleXML turns this
I have a bunch of posts stored in text files formatted in yaml/textile (from
We're building an app, our first using Rails 3, and we're having to build
I am trying to loop through a bunch of documents I have to put
I'm making a simple page using Google Maps API 3. My first. One marker
We are using XSLT to translate a RIXML file to XML. Our RIXML contains

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.