Python中的子进程添加变量

1 投票
4 回答
1002 浏览
提问于 2025-04-16 05:25

在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',可以分成日、月和年。有没有什么好主意呢?

提前谢谢你们

乔治

4 个回答

0

在编程中,有时候我们需要处理一些数据,这些数据可能来自不同的地方,比如用户输入、数据库或者其他程序。为了让程序能够理解这些数据,我们需要把它们转换成程序可以使用的格式。

这就像把一种语言翻译成另一种语言一样。比如,你可能会把英文的句子翻译成中文,这样说中文的人才能理解。程序也是一样,它需要把外部的数据转换成它能理解的格式,才能进行处理。

在这个过程中,我们可能会用到一些工具或者库,这些工具可以帮助我们更方便地进行数据转换。就像你在学习一门新语言时,可能会用到字典或者翻译软件,帮助你更快地理解和使用新语言。

总之,数据转换是编程中一个非常重要的步骤,它帮助我们把外部世界的数据转化为程序可以操作的信息。


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)
0

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?'

你可以使用strftime这个方法,从datetime模块中获取当前的时间和日期:

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

使用 % 格式化 来构建命令字符串。

>>> 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) )
>>> 

撰写回答