子過程在Python添加變量子過程在Python添加變量
import subprocess
subprocess.call('Schtasks /create /sc ONCE /tn Work /tr C:\work.exe /st 15:42 /sd 13/10/2010')
我希望能夠設置在上面的命令中的變量。變量是15和42分隔的'15:42'時間和'13/10/2010'日期在日,月和年分離的任何想法?
Thanx提前
喬治
子過程在Python添加變量子過程在Python添加變量
import subprocess
subprocess.call('Schtasks /create /sc ONCE /tn Work /tr C:\work.exe /st 15:42 /sd 13/10/2010')
我希望能夠設置在上面的命令中的變量。變量是15和42分隔的'15:42'時間和'13/10/2010'日期在日,月和年分離的任何想法?
Thanx提前
喬治
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)
使用%
formatting打造的命令字符串。
>>> 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))
>>>
'格式'方法是Python 2.6以來的首選:http://www.python.org/dev/peps/pep-3101/ – katrielalex 2010-10-13 13:56:51
Python具有高級的字符串格式功能,對字符串使用format
方法。例如:
>>> 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?'
您可以datetime
模塊中使用strftime
獲取時間和日期:
>>> import datetime
>>> now = datetime.datetime.now()
>>> now.strftime("%A %B %Y, %I:%M:%S")
'Wednesday October 2010, 02:54:30'
import time
subprocess.call(time.strftime("Schtasks /create /sc ONCE /tn Work /tr C:\work.exe /st %H:%M /sd %d/%m/%Y"))
如果你想改變的時候,你可以將它設置成時間對象,用它。
如何使時間和日期的字符串? – geocheats2 2010-10-13 13:37:43
-1通過合併它們來格式化字符串並不是唯一的一種明顯的方法。 – katrielalex 2010-10-13 13:56:10
@ geocheats2你可以使用datetime來設置字符串的含義是什麼:http://docs.python.org/library/datetime.html使用日期和時間對象以及字符串格式所需的方法是可能的 – jknair 2010-10-13 16:53:03