0
import time

number = 1
while number > 0:
    print "Testing" 
    time.sleep(5) #print every 5 seconds

That is just an example loop. I'm a semi-beginner and I'm not sure how to make a keypress(any key is fine) display how long the program has been running. This program will be running on Windows 7 and Linux.

Thank you very much.

3 Answers3

2

Welcome to Stack Overflow and to Python! You'll like it here.

First, I'll show you how to print out the time your code has been running. The time module includes a time() function that gets the current time as a Unix timestamp (the number of seconds since January 1, 1970). If you assign it to a variable at the start of the function, you can simply call it each time through the loop and subtract it from the current time to get your runtime. With me so far?

(You can also remove your number variable and the number > 0 check and simply replace it with True.)

import time

start_time = time.time()
while True:
    print "I've been running for %d seconds!" % (time.time() - start_time) 
    time.sleep(5) #print every 5 seconds

But you asked how to get it each time the user presses a key. If you just want 'enter', you can do:

import time

start_time = time.time()
while True:
    print "I've been running for %d seconds!" % (time.time() - start_time) 
    raw_input("Press Enter...")

The raw_input() function will wait for the user to press Enter, then print out the runtime.

Christian Ternus
  • 8,406
  • 24
  • 39
  • I'm not sure if this is possible, but if i press enter and it says "I've been running for 5 seconds" and then i press enter 10 seconds later, can python delete the initial output and change it to 15 seconds. (Trying to avoid a scrolling time output) – user1539175 Oct 17 '13 at 22:26
  • @user1539175, Take a look at http://stackoverflow.com/questions/6169217/replace-console-output-in-python – Bi Rico Oct 17 '13 at 22:36
  • @BiRico The problem is that given the example above using `raw_input`, you're using the Enter key to get the next line. The actual answer gets a lot more complicated if you want to avoid that. – Christian Ternus Oct 17 '13 at 22:39
  • @user1539175 Try combining the getch() code from http://stackoverflow.com/a/1394994/2797476 with Bi Rico's suggestion to print `\r` at the beginning of each line, then replace `raw_input` with a call to `getch()` as suggested in the comments to that answer. (You'll need to find a way to catch Ctrl-C if you don't want your program running forever.) Good luck! – Christian Ternus Oct 17 '13 at 22:44
  • @ChristianTernus, sorry you're right the method I pointed to is not compatible with raw_input. – Bi Rico Oct 17 '13 at 22:49
0

One problem at a time.

  1. How do you find how long your program has been running at the point at which you want to calculate?
  2. How do you detect a key-press?
  3. How do you get the program to produce 1) when 2) happens?

Try each problem in turn, then ask if you need help.

Fred Mitchell
  • 2,145
  • 2
  • 21
  • 29
0

There are a lot of complexities and approaches for a such a simple question.

If you are looking for up time of a currently running process, use the OS to query that process with the subprocess module to run a command line operation such as 'ps | grep "foo" '

Usually programs do only one thing at a time. For example, the code could either do work OR look for a keypress. If you need to run have to run two different sections of code concurrently, spawn (run) the code segments as separate threads . For your question you could spawn two threads (pieces of code), one to do work and one to query up time.

Use the threading module in python to wrap the worker function and create a query thread. However, when the worker thread is done, you will want the query thread to terminate also. One way to do this is to define it as a daemon thread. Daemon threads terminate when they are the only threads alive.

For example:

from time import sleep
import datetime
import threading


def do_someting():
    MAX_RUN_TIME = 300 #Seconds
    for i in xrange(MAX_RUN_TIME):
        print i,
        sleep (1)


class worker_thread(threading.Thread):   

    def run(self):
        do_someting()


class keypress_daemon_thread(threading.Thread):   

    def __init__(self):
        threading.Thread.__init__(self) # Initialize the parent class 
        self.daemon = True #  Terminates if only daemon threads are left

    def run(self):
        startTime = datetime.datetime.now()
        while True:
            raw_input()
            timeDelta =  datetime.datetime.now() - startTime
            print 'Up for', timeDelta


if __name__ == '__main__':
    workerThread = worker_thread()
    keyPressThread = keypress_daemon_thread()
    workerThread.start()
    keyPressThread.start()
    workerThread.join()
Bruce Peterson
  • 344
  • 3
  • 8