2013-03-25 35 views
-2

执行此命令我有这样的命令,它运行在提示:如何从Python的

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

我如何能够执行从一个Python程序?

在我的节目我创建了一个日期,CONCAT,为一个字符串,像这样

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

粘贴您的整个python脚本?你使用datetime来创建你的时间(使用createnewtime())的自定义函数吗?另外,最终目标是什么?真的只是打印这个标准输出?你是否试图通过sys/os模块“回显”这个? – 2013-03-25 15:35:54

+0

为什么从python脚本运行python脚本?如果你真的想执行该命令,请参阅http://stackoverflow.com/questions/89228/calling-an-external-command-in-python。但我建议将setHeater.py中的内容导入到当前脚本中,并使用Python进行计划。否则,你有不必要的开销。 – 2013-03-25 15:38:05

+0

@Jonathan我不想从我的python脚本运行python脚本,我正在尝试为我的脚本安排下一次运行 – Michel 2013-03-25 15:41:53

回答

1

您可以使用操作系统库:

import os 

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

虽然如果您尝试执行此操作你不需要使用“回声”。只需:

import os 

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

没有回波,该命令是否执行并安排? – Michel 2013-03-25 16:17:12

+0

这实际上起作用,是不是我在某个地方读过“不如使用os.system()更好”? – Michel 2013-03-25 18:02:48

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

而不是显式运行setHeater.py,使用'import sys'然后'sys.argv [0]' - 这意味着如果您更改名称,脚本仍然可以工作。 – 2013-03-25 15:52:33

+0

当我运行这个,我得到这个结果: – Michel 2013-03-25 16:02:23

+0

'/ usr/bin/python /home/setHeater.py echo“/ usr/bin/python /home/setHeater.py”|在17:01 回溯(最近通话最后一个): 文件 “/home/setHeater.py”,第6行,在 RETURNCODE =调用(commandToExecute) 文件“/usr/lib/python2.7/subprocess。 pyray“,第493行,致电 返回Popen(* popenargs,** kwargs).wait() 文件”/usr/lib/python2.7/subprocess.py“,第679行,在__init__中 errread,errwrite) 文件 “/usr/lib/python2.7/subprocess.py”,线1259,在_execute_child 加注child_exception OSERROR:[错误2]没有这样的文件或directory' – Michel 2013-03-25 16:02:48