2013-10-23 44 views
0

我想执行一个脚本使用子程序,我知道的作品,当我手工执行;以下是我的调用脚本:试图执行Python脚本使用子进程(Django)

# the command string we want to issue to ffmpeg.py to generate our ffmpeg command strings 
     commandString = [ 
      'python', 
      os.path.join(SCRIPT_DIR, 'ffmpeg.py'), 
      '-i', os.path.join('/srv/nfsshare/transcode50', userFolder, directory, title), 
      '-d', os.path.join('/srv/nfsshare/transcode50', userFolder, directory), 
      '-r', request.POST['framerate'], 
      '-p 2', '-f', ",".join(formats), '-t', ",".join(rasters) 
     ] 

     # call transcode50 script to generate condor_execute.py 
     subprocess.call(' '.join(commandString) + ' > /srv/nfsshare/transcode50/output.txt', shell=True) 

实际的脚本本质上会生成一个命令字符串列表并将它们输出到控制台。我将输出传送到一个名为output.txt的文件中,在该命令字符串的末尾进行测试,因为我从Django运行Python代码,并且无法实时查看shell输出,但是当我检查文件时时间,没有任何东西在那里,副作用被调用的脚本也没有(生成一个Python文件)不会发生。因此,我相信我可能会或可能不会考虑使用子流程模块,也许它是Django特有的?

+0

为什么你要做这个子进程调用而不是简单地导入脚本并调用它? –

+0

我可以导入这个脚本,这可能会起作用,但它会生成一个新的Python脚本,无论如何都需要运行,所以这个问题仍然需要解决才能执行新的脚本,除非您有任何关于一旦“会话”开始运行一个生成的Python脚本(即,保存一个新的script.py文件,但仍然能够在生成它的相同脚本中打开并执行它)。 – coltonoscopy

+0

你可能会解释发生了什么情况。 – tdelaney

回答

1

使用''.join(...)将列表转换为shell字符串是有风险的,因为列表中可能有某些内容(如文件名中的空格)需要shell转义。你最好坚持使用命令列表而不是shell。你还应该捕获哪些是好东西的地方。最后使用check_call并将整个事件包装在一个记录执行失败的异常处理程序中。

try: 
    commandString = [ 
     'python', 
     os.path.join(SCRIPT_DIR, 'ffmpeg.py'), 
     '-i', os.path.join('/srv/nfsshare/transcode50', userFolder, directory, title), 
     '-d', os.path.join('/srv/nfsshare/transcode50', userFolder, directory), 
     '-r', request.POST['framerate'], 
     '-p 2', '-f', ",".join(formats), '-t', ",".join(rasters) 
    ] 

    # call transcode50 script to generate condor_execute.py 
    subprocess.check_call(commandString, 
     stdout=open('/srv/nfsshare/transcode50/output.txt', 'w'), 
     stderr=subprocess.STDOUT) 

except Exception, e: 
    # you can do fancier logging, but this is quick 
    open('/tmp/test_exception.txt', 'w').write(str(e)) 
    raise 
相关问题