簡體   English   中英

寫入文件和運行文件有時會起作用,大多數情況下只有第一個

[英]Writing to file and running the files sometimes works, mostly only first one

這段代碼在大多數情況下會產生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

>>> 
"""

六邊形化是使用此腳本完成的,有時似乎會產生奇數個半字節,這似乎也很奇怪。

# bootstrapper for running hexlified executables,
# hexlification can be done by running this file directly or calling function make
# running can be done by run function in runner module, which imports the code,
# runs them from temporary files

import os

modulename = 'codefiles.py'

def code_file_names(d='.', ext='.exe'):
    return [n for n in os.listdir(d)
                            if n.lower().endswith(ext)]

def make():
    codes = code_file_names(os.curdir)
    with open(modulename, 'a') as f:
        f.write('exes = (')
        hex_codes = [open(n, 'rb').read().encode('hex') for n in codes]
        assert all(len(c) & 1 == 0 for c in hex_codes)
        print len(hex_codes),map(len, hex_codes)
        hex_codes = [repr(c) for c in hex_codes]
        f.write(',\n'.join(hex_codes))
        f.write(')\n')


if __name__ == '__main__':
    import make_exe

    # prepare hexlified exes for exes  in directory if codefiles not prepared
    if modulename not in os.listdir('.'):
        try:
            os.remove(modulename)
        except:
            pass   
        make()

    # prepare script for py2_exe to execute the scripts by run from runner
    make_exe.py2_exe('runner.pyw', 'tools/dvd.ico')        

在Martelli先生的建議之后,我的錯誤消失了,但仍然沒有得到預期的結果。

我通過新版本的代碼來創建exe文件(如果存在)(在新的創建例程中保存了文件名)。 創建文件時,它會同時啟動兩個代碼(兩個十六進制代碼),但之后會同時復制多個第一個代碼。

tempfile.mktemp()除了由於其安全性問題已被棄用多年之外,還保證僅在程序的一次運行中使用唯一名稱,因為根據https://docs.python.org/2/library/tempfile.html #tempfile.mktemp ,“該模塊使用一個全局變量來告訴它如何構造一個臨時名稱”。 因此,在第二次運行時,很清楚的錯誤消息告訴您,“該進程無法訪問該文件,因為該文件正在被另一個進程使用”(特別是,該進程是由上一次運行啟動的,即您無法重寫.exe ,目前正在某些進程中運行)。

解決方法是確保每次運行都將其自己的唯一目錄用於臨時文件。 請參閱https://docs.python.org/2/library/tempfile.html#tempfile.mkdtemp上的 mkdtemp 最終如何清理這些臨時目錄是一個不同的問題,因為只要任何進程正在該目錄中運行.exe文件,就無法做到這一點-您可能需要一個單獨的“清理腳本”盡其所能,定期運行(例如,在Unix中,我將使用cron )和存儲庫(例如,小型sqlite DB甚至只是一個文件)運行,以記錄先前運行中創建的哪些臨時目錄仍然存在,並且需要清除(捕獲尚無法清除的異常,以便將來重試)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM