我如何从Python执行此命令

时间:2013-03-25 15:33:07

标签: python python-2.7

我有这个命令在提示符上运行:

echo "python setHeater.py" | at 16:30

如何从Python程序执行该操作?

在我的程序中,我创建了一个日期,并将其连接到字符串,类似这样的

newtime = createnewtime()
commandToExecute = 'echo "python setHeater.py" | at ' + newtime 
#and then here the code to actually run the command in the command environment

2 个答案:

答案 0 :(得分:1)

基本上你可以使用subprocess库执行命令,如:

from subprocess import Popen, PIPE

newtime = createnewtime()
p1 = Popen(["echo ", "'python setHeater.py'"], stdout=PIPE)
p2 = Popen(["at", newtime ], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]

答案 1 :(得分:1)

您可以使用操作系统库:

import os

newtime = createnewtime()
command = 'echo "python setHeater.py" | at ' + newtime
os.system(command)

虽然如果您尝试执行此命令,则不需要使用“echo”。简单地:

import os

newtime = createnewtime()
command = "python setHeater.py | at " + newtime
os.system(command)