2013-10-23 43 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 
相關問題