views:

57

answers:

4

Subprocess in Python Add Variables

import subprocess
subprocess.call('Schtasks /create /sc  ONCE  /tn  Work  /tr C:\work.exe /st 15:42 /sd 13/10/2010')

I want to be able to set the variables on the above command. the variables are the time '15:42' separated in 15 and 42 and the date '13/10/2010' separated in day , month and year any ideas??

Thanx in advance

George

A: 

import subprocess 
time = "15:42"
date = "13/10/2010"
# you can use these variables anyhow take input from user using raw_iput()
subprocess.call('Schtasks /create /sc ONCE /tn Work /tr C:\work.exe /st '+time+' /sd '+date)
jknair
how to make string of time and date?
geocheats2
-1 Formatting strings by summing them isn't the one and only one obvious way to do it.
katrielalex
@geocheats2 what do u mean by make string of u can use datetime : http://docs.python.org/library/datetime.html for using date and time objects and teh required methods for the string format is possible
jknair
A: 

Use % formatting to build the command string.

>>> hour,minute = '15','42'
>>> day,month,year = '13','10','2010'
>>> command = 'Schtasks /create /sc  ONCE  /tn  Work  /tr C:\work.exe /st %s:%s /sd %s/%s/%s'
>>> command % (hour,minute, day,month,year)
'Schtasks /create /sc  ONCE  /tn  Work  /tr C:\\work.exe /st 15:42 /sd 13/10/2010'
>>> subprocess.call( command % (hour,minute, day,month,year) )
>>> 
gimel
The `format` method is preferred since Python 2.6: http://www.python.org/dev/peps/pep-3101/
katrielalex
A: 

Python has advanced string formatting capabilities, using the format method on strings. For instance:

>>> template = "Hello, {name}. How are you today, {date}?"
>>> name = "World"
>>> date = "the fourteenth of October"
>>> template.format(name=name, date=date)
'Hello, World. How are you today, the fourteenth of October?'

You can get the time and date using strftime in the datetime module:

>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime("%A %B %Y, %I:%M:%S")
'Wednesday October 2010, 02:54:30'
katrielalex
A: 
import time

subprocess.call(time.strftime("Schtasks /create /sc  ONCE  /tn  Work  /tr C:\work.exe /st %H:%M /sd %d/%m/%Y"))

If you would like to change the time you can set it into time object and use it.

Version Control Buddy