import os import win32com.client as client from flask import Flask from flask import request app = Flask(__name__) shell = client.Dispatch("WScript.Shell") @app.route('/') def getShortCut(): #filename = request.values.get('filename') #filename = filename.replace('/', '//') #lnkname = filename.split('//')[-1].split('.')[0] + '.lnk' filename = 'D://eclipse//eclipse.exe' lnkname = 'd://eclipse//eclipse2021.lnk' print(filename) print(lnkname) createShortCut(filename, lnkname) return "<h1>Sucess!</h1>" def createShortCut(filename, lnkname): """filename should be abspath, or there will be some strange errors""" filename = os.path.abspath(filename) shortcut = shell.CreateShortCut(lnkname) shortcut.TargetPath = filename shortcut.save() return os.path.abspath(lnkname) if __name__ == "__main__": app.run()
运行之后请求报错:
[2021-07-20 13:48:30,177] ERROR in app: Exception on / [GET] Traceback (most recent call last): File "D:\pythonworks\wmpythondemo\lib\site-packages\flask\app.py", line 2447, in wsgi_app response = self.full_dispatch_request() File "D:\pythonworks\wmpythondemo\lib\site-packages\flask\app.py", line 1952, in full_dispatch_request rv = self.handle_user_exception(e) File "D:\pythonworks\wmpythondemo\lib\site-packages\flask\app.py", line 1821, in handle_user_exception reraise(exc_type, exc_value, tb) File "D:\pythonworks\wmpythondemo\lib\site-packages\flask\_compat.py", line 39, in reraise raise value File "D:\pythonworks\wmpythondemo\lib\site-packages\flask\app.py", line 1950, in full_dispatch_request rv = self.dispatch_request() File "D:\pythonworks\wmpythondemo\lib\site-packages\flask\app.py", line 1936, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "D:/pythonworks/wmpythondemo/win32/win32demo.py", line 20, in getShortCut createShortCut(filename, lnkname) File "D:/pythonworks/wmpythondemo/win32/win32demo.py", line 27, in createShortCut shortcut = shell.CreateShortCut(lnkname) File "<COMObject WScript.Shell>", line 2, in CreateShortCut pywintypes.com_error: (-2147352567, '发生意外。', (0, None, None, None, 0, -2147221008), None) 127.0.0.1 - - [20/Jul/2021 13:48:30] "GET / HTTP/1.1" 500 -
可以通过:
来查看具体错误信息为:
这是由于多线程使用pywin32com造成的问题。
只要在线程启动时先运行pythoncom.CoInitialize()就没有问题了。
在代码中可以使用: