此代码在大多数情况下都会产生WindowsError,很少(就像第一次运行时一样)不会。在
""" Running hexlified codes from codefiles module prepared previously """
import tempfile
import subprocess
import threading
import os
import codefiles
if __name__ == '__main__':
for ind, c in enumerate(codefiles.exes):
fn = tempfile.mktemp() + '.exe'
# for some reason hexlified code is sometimes odd length and one nibble
if len(c) & 1:
c += '0'
c = c.decode('hex')
with open(fn, 'wb') as f:
f.write(c)
threading.Thread(target=lambda:subprocess.Popen("", executable=fn)).start()
""" One time works, one time WindowsError 32
>>>
132096 c:\docume~1\admin\locals~1\temp\tmpkhhxxo.exe
991232 c:\docume~1\admin\locals~1\temp\tmp9ow6zz.exe
>>> ================================ RESTART ================================
>>>
132096 c:\docume~1\admin\locals~1\temp\tmp3hb0cf.exe
Exception in thread Thread-1:
Traceback (most recent call last):
File "C:\Python27\lib\threading.py", line 810, in __bootstrap_inner
self.run()
File "C:\Python27\lib\threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "C:\Documents and Settings\Admin\My Documents\Google Drive\Python\Tools\runner.pyw", line 18, in <lambda>
threading.Thread(target=lambda:subprocess.Popen("", executable=fn)).start()
File "C:\Python27\lib\subprocess.py", line 710, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 958, in _execute_child
startupinfo)
WindowsError: [Error 32] The process cannot access the file because it is being used by another process
991232 c:\docume~1\admin\locals~1\temp\tmpnkfuon.exe
>>>
"""
六边形是用这个脚本来完成的,它有时似乎会产生奇数个啃痕,这似乎也很奇怪。在
^{pr2}$经过马尔泰利先生的建议,我得到的错误消失了,但仍然没有预期的结果。在
我在新版本的代码中传递exe文件的创建(保存在新创建例程中的文件名)。它在创建文件时同时启动两个代码(两个六边形代码),但之后会启动第一个代码的多个副本。在
tempfile.mktemp()
除了由于其安全问题而被弃用多年之外,它只保证在程序的一次运行中具有唯一的名称,因为根据https://docs.python.org/2/library/tempfile.html#tempfile.mktemp,“模块使用一个全局变量来告诉它如何构造一个临时名称”。因此,在第二次运行时,正如非常清晰的错误消息告诉您的那样,“该进程无法访问该文件,因为它正被另一个进程使用”(具体地说,该进程是由上一次运行启动的,即您不能重写当前正在某个进程中运行的.exe
)。在解决方法是确保每次运行都为临时文件使用自己的唯一目录。参见
mkdtemp
,位于https://docs.python.org/2/library/tempfile.html#tempfile.mkdtemp。如何最终清理这些临时目录是一个不同的问题,因为只要任何进程在这样一个目录中运行.exe
文件,这是不可能完成的,你可能需要一个单独的“清理脚本”来完成它所能做的事,定期运行(例如在Unix中,我使用cron
)和一个存储库(例如一个小的sqlite
DB,甚至只是一个文件)来记录在以前的运行中创建的临时目录中哪些仍然存在并且需要清除(捕捉那些还不能清理的异常,以便将来重试)。在相关问题 更多 >
编程相关推荐