2014-02-21 47 views
0

的工作方式不同要按下面的代碼運行在python腳本二進制:subprocess.call()的腳本和解釋

def runner(output_file): 
    result = 1 

    try: 
     image_name = re.sub(r'\..*', '.png', output_file) 
     args = ['dot', output_file, '-Tpng', '-o', image_name] 
     result = subprocess.call(args) 

     if(result == 0): 
      print('Graph is rendered to {0}'.format(image_name)) 

    except: 
     print('ERROR: Cannot run DOT. Please check your PATH') 

    return result 

當我調用該函數返回0,一切似乎是好了,但沒有文件產生

當我從Python解釋器相同的:

Python 2.7.5+ (default, Sep 19 2013, 13:48:49) 
[GCC 4.8.1] on linux2 
Type "help", "copyright", "credits" or "license" for more information. 
>>> output_file = 'out.dot' 
>>> image_name = 'out.png' 
>>> args = ['dot', output_file, '-Tpng', '-o', image_name] 
>>> subprocess.call(args) 

文件被成功生產。

我試圖設置一個不正確的名稱,並得到腳本中的錯誤(如預期)。從腳本調用pwd給了我一個正確的目錄。使用硬編碼值調用與使用變量調用相同。

我在做什麼錯?

+0

也許你應該運行shell = True? –

+0

在調用'subprocess.call'前嘗試'打印args' – thefourtheye

+0

@thefourtheye'['dot','out.dot','-Tpng','-o','out.png']' – Alex

回答

0

以下是可能的幫助。我的經驗args = [...]是容易出錯的。

shlex.split('dot {0} -Tpng -o {1}'.format(input_file, image_name)) 

通常更健壯。但它要求你正確地轉義文件名中的空格...

第二個:你的輸入和輸出文件是否在你的參數中顛倒了?還是剛剛命名的變量很差?

第三請爲python的禪宗和你自己的理智的緣故不要做diaper antipattern例如, except:

:依託$PATH和/或使用二進制非絕對路徑,勢必在某一時刻打破 - 使用全/path/to/dot作爲你的第一個參數。

+1

我完全不同意「shlex」方法的穩健性。你必須小心,但如果你這樣做,事情會更好 - 特別是,如你所說,與文件名和他們的逃跑。 – glglgl

+0

shlex.split()沒有幫助。你認爲應該如何使用它? – Alex