2014-02-21 49 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