用Python打开p文件

0 投票
1 回答
576 浏览
提问于 2025-04-17 06:52

这让我感到困惑。

我有一个Python脚本,它在Windows平台上工作,主要是生成一个XML文件,下载一些图片,然后调用一个外部的控制台应用程序,用这些XML和图片生成一个视频。

我用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秒后,输出却是[]。

同样的代码,只是放在了不同脚本的末尾……

编辑:感谢Dave、Dgrant和ThomasK,似乎是生成脚本没有关闭文件,因为重定向错误输出到标准输出时显示了这一点:

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...")   

任何帮助都将不胜感激。

1 个回答

4

你没有关闭文件。你的代码是:

xmlfileObj.close

但应该是:

xmlfileObj.close()

补充说明:为了更清楚地说明一下,代码 xmlfileObj.close 是一个有效的 Python 表达式,它返回一个指向文件(或类似文件的对象)内置 close 方法的引用。虽然这个表达式是合法的代码,但它并不会实际执行任何操作。具体来说,它并不会真正调用 close() 方法。你需要加上括号才能让它真正执行。

撰写回答