写入Python的“with”子句并随后由C进程读取的文件被锁定。有什么可能的原因吗?

2024-09-27 20:19:17 发布

您现在位置:Python中文网/ 问答频道 /正文

使用以下代码在Python进程中创建并写入新的XML文件:

with open(filepath, 'w') as f:
    f.write(inXmlStr)

随后,Python进程启动了一个C#进程:

with open(self.outputLogPath, 'w') as f:
    self.csharpProcess = subprocess.Popen(processOpenCmd, stdout=f)

这个C进程使用XmlDocument类读取这个新创建的XML文件:

XmlDocument chXml = new XmlDocument();
chXml.Load(channelXml);

但是,有时会发现文件被锁定,无法被C进程读取。通过使用Handle可以发现,锁定XML文件的进程实际上是最初创建并写入该文件的Python进程。这是出乎意料的,因为Python的“with”子句应该正确地关闭所有打开的文件。因此,我怀疑这是一个Python错误。你知道吗

我正在使用Python2.7和.NETFramework 4开发Windows7

C进程的异常stacktrace如下所示:

System.IO.IOException: The process cannot access the file 'C:\...\...\channel.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, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
at System.Threading.CompressedStack.runTryCode(Object userData)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
at System.Xml.XmlTextReaderImpl.OpenUrl()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
at System.Xml.XmlDocument.Load(XmlReader reader)
at System.Xml.XmlDocument.Load(String filename)
at ChannelXmlRun(String xmlFile)

你知道为什么会这样吗?也许这是一个已知的Python错误,你可以告诉我?你知道吗


Tags: 文件iostringobjectaccess进程withload

热门问题