2011-11-22 60 views
0

这让我感到莫名其妙。用python打开

我有一个python脚本,在Windows平台上执行一些工作来生成XML文件,下载一些图像,然后调用外部控制台应用程序来使用xml和python脚本生成的图像生成视频。

我用pOPen调用的应用程序应该返回一个状态,即[成功]或[无效]或[失败],取决于它如何解释我传递的数据。

如果我使用我的生成脚本来生成信息,然后在另一个脚本中分别调用控制台应用程序,它会正常工作,我会成功并生成一个视频。

成功的代码(请忽略测试打印!):

print ("running console app...") 

cmd = '"C:/Program Files/PropertyVideos/propertyvideos.console.exe" -xml data/feed2820712.xml -mpeg -q normal' 
print (cmd) 
p = subprocess.Popen(cmd , stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
output = p.communicate()[0] 
print ("\n----\n[" + output + "]\n----\n") 

if output == "[success]": 
    print "\nHURRAHHHHH!!!!!!!" 

print ("finished...") 

但是,如果我有相同的代码,在生成的信息养活控制台应用程序脚本的末尾,则它运行约2秒,输出= []

相同的代码,只是跑在不同的脚本结束...

编辑: 感谢戴夫,Dgrant和ThomasK它似乎是在生成脚本不打烊该文件作为重定向NG strerr到stdout显示:

Unhandled Exception: System.IO.IOException: The process cannot access the file ' 
C:\videos\data\feed2820712.xml' because it is being used by another process. 
    at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) 
    at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, I 
nt32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions o 
ptions, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy) 

但是我将结束文件: 摘自生成脚本:

xmlfileObj.write('</FeedSettings>\n') # write the last line 
    xmlfileObj.close 

    # sleep to allow files to close 
    time.sleep(10) 

    # NOW GENERATE THE VIDEO 
    print ("initialising video...") 

    cmd = '"C:/Program Files/PropertyVideos/propertyvideos.console.exe" -xml data/feed2820712.xml -mpeg -q normal' 
    print (cmd) 
    p = subprocess.Popen(cmd , stdout=subprocess.PIPE, stderr=subprocess.STDOUT) 
    output = p.communicate()[0] 
    print ("\n----\n[" + output + "]\n----\n") 

    if output == "[success]": 
     print "\nHURRAHHHHH!!!!!!!" 

    print ("finished...") 

任何帮助,将不胜感激。

+3

我想你或者需要'shell = True',或者将你的命令分解成参数列表。 –

+0

@ThomasK - 谢谢 - 但它在一个单独的脚本中工作 - 即上面的工作。但是,当我将代码粘贴到具有相同包含/模块的另一个脚本中时,我得不到任何结果。 – dan360

+1

这是不相关的,但你可以通过stderr = subprocess.stdout来将它重定向到stdout,因为就像现在一样,你正在丢弃stderr。 – dgrant

回答

4

你没有关闭文件。您的代码表示:

xmlfileObj.close 

当它应该是

xmlfileObj.close() 

编辑:只是为了澄清 - 该代码xmlfileObj.close是一个有效的Python表达式返回到内置的close方法的引用文件(或文件)对象。由于它是一个有效的python表达式,它是完全合法的代码,但它没有任何副作用。具体来说,它没有实际调用close()方法的效果。您需要包含打开和关闭的括号才能做到这一点。

+0

哦,因为这里的<插入本尊>的爱。你盯着一段代码几个小时,只是看不到那么简单! - 非常感谢。 – dan360

+0

我曾经看到过一个庞大的代码库,其中包含fp.flush,随后在整个代码库中散布了fp.close。巨大的facepalm,但事实证明它从来没有真正重要,它主要是写出日志,当脚本退出时它会被关闭(即它们从未被脚本读取) – dgrant