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

  • Home
  • SEARCH
  • 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 8726861
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T08:19:54+00:00 2026-06-13T08:19:54+00:00

I have a python script that executes linux commands with timeout using a while

  • 0

I have a python script that executes linux commands with timeout using a while loop and sleep like below

fout = tempfile.TemporaryFile()
try:
    p = subprocess.Popen(["/bin/bash","-c", options.command], bufsize=-1, shell=False, preexec_fn=os.setsid, stdin=subprocess.PIPE, stdout=fout, stderr=subprocess.PIPE)
except:
    sys.exit(UNEXPECTED_ERROR)
if options.timeout:
    print "options.timeout = %s" % options.timeout
    elapsed = 0
    time.sleep(0.1) # This sleep is for the delay between Popen and poll() functions
    while p.poll() is None:
        time.sleep(1)
        elapsed = elapsed + 1
        print "elapsed = %s" % elapsed
        if elapsed >= options.timeout:
            # TIMEDOUT
            # kill all processes that are in the same child process group
            # which kills the process tree
            pgid = os.getpgid(p.pid)    
            os.killpg(pgid, signal.SIGKILL)
            p.wait()
            fout.close()
            sys.exit(TIMEOUT_ERROR)
            break
else:
    p.wait()

fout.seek(0) #rewind to the beginning of the file
print fout.read(),
fout.close()
sys.exit(p.returncode)

$ time myScript -c "cat file2" 2>&1 -t 5
options.timeout = 5
elapsed = 1

real    0m11.811s
user    0m0.046s
sys     0m1.153s

My question is in that above case even if the timeout is 5 seconds cat continues till it finishes. Am I missing something here? Please help.

  • 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-06-13T08:19:56+00:00Added an answer on June 13, 2026 at 8:19 am

    It works as expected on Ubuntu:

    $ /usr/bin/ssh root@localhost -t 'sync && echo 3 > /proc/sys/vm/drop_caches'
    $ /usr/bin/time python2.4 myscript.py 'cat big_file'
    timeout
    done
    0.01user 0.63system 0:05.16elapsed 12%CPU 
    
    $ /usr/bin/ssh root@localhost -t 'sync && echo 3 > /proc/sys/vm/drop_caches'
    $ /usr/bin/time cat big_file >/dev/null
    0.02user 0.82system 0:09.93elapsed 8%CPU
    

    It also work with a shell command:

    $ /usr/bin/time python2.4 myscript.py 'while : ; do sleep 1; done'
    timeout
    done
    0.02user 0.00system 0:05.03elapsed 0%CPU
    

    Assumptions:

    • you can’t use time.time() due to possibility of a system clock change

    • time.clock() doesn’t measure children times on Linux

    • we can’t emulate time.monotonic() from Python 3.3 in pure Python
      due to ctypes is not available on Python 2.4

    • it is acceptable to survive hibernation e.g., 2 seconds before hibernation + 3 seconds after computer wakes up whenever it happens if timeout is 5 seconds.

    #!/usr/bin/env python2.4
    import os
    import signal
    import sys
    import tempfile
    import time
    from subprocess import Popen
    
    class TimeoutExpired(Exception):
        pass
    
    def wait(process, timeout, _sleep_time=.1):
        for _ in xrange(int(timeout * 1. / _sleep_time + .5)):
            time.sleep(_sleep_time)  # NOTE: assume it doesn't wake up earlier
            if process.poll() is not None:
                return process.wait()
        raise TimeoutExpired  # NOTE: timeout precision is not very good
    
    f = tempfile.TemporaryFile() 
    p = Popen(["/bin/bash", "-c", sys.argv[1]], stdout=f, preexec_fn=os.setsid,
              close_fds=True)
    try:
        wait(p, timeout=5)
    except TimeoutExpired:
        print >>sys.stderr, "timeout"
        os.killpg(os.getpgid(p.pid), signal.SIGKILL)
        p.wait()
    else:
        f.seek(0)
        for line in f:
            print line,
    f.close()  # delete it
    print >>sys.stderr, "done"
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a Python script that needs to issue a number of shell commands.
I have a Python script that is using some closed-box Python functions (i.e. I
I have a python script start.py that executes well from the command line. There
I have a working Python script that executes an external command and calls Popen.communicate()
I have the following query that I'm executing using a Python script (by using
Here is my problem: I have got a Python build script that executes several
I have a simple python script that works fine on Linux, I moved it
If I have a python script that is executed via a symlink, is there
I have a python script that runs a program, which generates few .exe files
I have a python script that I want always to run in the background.

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.