1

first of all, sorry for the imprecise title (if someone has a better suggestion how to name this thread feel free to tell me), my question is not that complicated at all.

I wrote a small program in Python where i execute a command line:

import os

os.system("sudo rtcwake -m off -s 100")

As some of you may know it is simply an rtcwake command that shuts down the computer and turns it on again (after 100 seconds).

I would like to implement this program in a way that when executed (from the console for example) the user gets to enter the number of seconds the computer should be down, instead of having the 100 seconds predetermined.

What is the correct way to do this?

2 Answers 2

1

format is your friend:

import os, sys 
if len(sys.argv) == 2:
  os.system("sudo rtcwake -m off -s {}".format(sys.argv[1]))
else: print "usage: ..."

so the seconds are command line parameters. Or, you can make it interactive:

import os
secs = raw_input()
os.system("sudo rtcwake off -s {}".format(secs))

to verify that the user input is an integer:

try:    secs = int(secs)
except: print 'usage: '
Sign up to request clarification or add additional context in comments.

2 Comments

Regarding your interactive variable, if the user enters anything which is not a number, the commando line gets in trouble. How would you check for this? I thought on executing an "if type(secs) is int -> os.system("sudo.....) else print 'incorrect, try again' os.system("python nameoftheprogram.py") but as i am reading making typechecks on python is not recomended...?
@user2013394, the type is str after the raw_input even if the input is a valid integer. added a possible check in the example.
1

use ArgumentParser

parser = argparse.ArgumentParser(description='Shutdown your computer and turns it on after x seconds.')
parser.add_argument('delay', metavar='x', type=int,
                   help='The number of seconds the computer should be down.', default=100)
args = parsre.parse_args()
x = args.delay

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.