def makePaperReport(self, paperResult): ##paperResult内数据:考试时间,班级,题号,正确答案,正确率,A选项率,B选项率,C选项率,D选项率,总人数,总题数 for i, r in enumerate(paperResult): classname = r[1] examid = r[0] stuCount = r[10] quesCount = r[9] self.sheet["A%d" % (i + 5)].value = r[2] # 题号 self.sheet["B%d" % (i + 5)].value = r[3] # 正确答案 self.sheet["C%d" % (i + 5)].value = r[4] # 正确率 self.sheet["D%d" % (i + 5)].value = r[5] # A选项率 self.sheet["E%d" % (i + 5)].value = r[6] # B选项率 self.sheet["F%d" % (i + 5)].value = r[7] # C选项率 self.sheet["G%d" % (i + 5)].value = r[8] # D选项率 self.sheet["B2"].value = stuCount # 总人数 self.sheet["G2"].value = quesCount # 总题数 self.sheet["B3"].value = examid # 考試時間 self.sheet["G3"].value = classname # 班級 file = r'tmp\\' + classname + examid + r'试卷分析.xlsx' self.wb.save(file) win32api.ShellExecute(0, 'open', file, '', '', 1)
def printPage(page): try: # with Path("first_page.pdf").open(mode="wb") as output_file: # pdf_writer.write(output_file) GHOSTSCRIPT_PATH = "D:\GHOSTSCRIPT\binswin32.exe" GSPRINT_PATH = "D:\GSPRINT\gsprint.exe" filename = tempfile.mktemp(".pdf") pdf_writer = PdfFileWriter() pdf_writer.addPage(page) with open(filename, "wb") as f: pdf_writer.write(f) # os.startfile(filename, "print") # YOU CAN PUT HERE THE NAME OF YOUR SPECIFIC PRINTER INSTEAD OF DEFAULT currentprinter = win32print.GetDefaultPrinter() win32api.ShellExecute(0, "printto", filename, '"%s"' % currentprinter, ".", 0) # win32api.ShellExecute(0, 'open', GSPRINT_PATH, '-ghostscript "'+GHOSTSCRIPT_PATH+'" -printer "'+currentprinter+filename, '.', 0) except Exception as e: return 1
def startHook(self): ''' 开始录制流程 ''' import hooker.Hook as H self.initProcess() autoType = cf.get_value("autoType") print("本次录制类型:", autoType) cf.set_value("autoType", autoType) if autoType == "Windows": HK = H.Hooker() HK.hooks() elif autoType == "IE": IEXPath = parentDirPath + r"\tools\IEXPath.exe" win32api.ShellExecute(0, 'open', IEXPath, '', '', 1) HK = H.Hooker() HK.hooks() elif autoType == "Chrome" or autoType == "Firefox": Init().hooks() from hooker.Extension import run run() else: pass
def get_doc(message): try: if message.content_type == 'photo': doc_id = message.photo[-1].file_id else: doc_id = message.document.file_id #get info about file doc = bot.get_file(doc_id) #download it filename = wget.download( 'https://api.telegram.org/file/bot{0}/{1}'.format( API_TOKEN, doc.file_path)) #get file path on host file_path = os.path.join(os.getcwd(), filename) #print it with default printer win32api.ShellExecute(0, "print", file_path, None, ".", 0) #Send messsage that everything is ok bot.send_message(message.from_user.id, "Printed!") except Exception as error: #if something went wrong send error message with a reason bot.send_message(message.from_user.id, 'Error! \nAdditional information: {}'.format(error))
def launch(self) -> None: iqfeed_args = "-product %s -version %s, -login %s -password %s" % ( self.product, self.version, self.login, self.password) if self.autoconnect: iqfeed_args = "%s -autoconnect" % iqfeed_args if self.savelogininfo: iqfeed_args = "%s -savelogininfo" % iqfeed_args if os.name == 'nt': # noinspection PyUnresolvedReferences import win32api # noinspection PyUnresolvedReferences import win32con win32api.ShellExecute(0, "open", "IQConnect.exe", iqfeed_args, "", win32con.SW_SHOWNORMAL) elif os.name == 'posix': import subprocess iqfeed_call = "wine iqconnect.exe %s" % iqfeed_args subprocess.Popen(iqfeed_call, shell=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) time.sleep(5)
def print_file(self): text_report = self.edit_space.get("1.0", 'end-1c') tkm.showinfo('Message Info', 'Printing and Saving the Report') local_time = time.strftime("%m_%d_%Y_%H_%M_%S") pdf_file_name = "Report " + str(local_time) + ".pdf" doc = SimpleDocTemplate(pdf_file_name) styles = getSampleStyleSheet() h3 = styles["h3"] normal = styles["Normal"] text = text_report # print(text) story = [Paragraph("Report", h3)] if text: story.append(Paragraph(text, normal)) story.append(Spacer(1, 0.1 * inch)) doc.build(story) win32api.ShellExecute(0, "print", pdf_file_name, None, ".", 0)
def cf_start(input=None): #open a program or a file input = str(input).lower() if input == "": return pathlist = getPathlist() #check if input is in pathlist result = comparisonAlgorithm(pathlist, input) returnvalue = [] if result != False: shellreturn = win32api.ShellExecute(0, None, result[1], None, None, 1) if shellreturn > 32: returnvalue = [True, result[0], result[1], result[2], result[3]] else: returnvalue = [False, result[0], result[1], result[2], result[3]] else: returnvalue = [False, "No match found", ""] return returnvalue
def file_print(fullpath, printer: str = None, use_alternative: bool = False) -> bool: ''' Prints file on specified printer. Non-blocking. Returns True on success. If no printer is specified - print on system default printer. ''' fullpath = _fix_fullpath(fullpath) if ' ' in fullpath: fullpath = f'"{fullpath}"' if not printer: try: printer = win32print.GetDefaultPrinter() except RuntimeError: return False verb = 'print' printer_str = f'"/d:{printer}"' if use_alternative: verb = 'printto' printer_str = f'"{printer}"' win32api.ShellExecute(0, verb, fullpath, printer_str, '.', 0) return True
def PrintFile1(e): import win32print import sys import win32api from tkinter import messagebox printer_name = win32print.GetDefaultPrinter() mes = messagebox.askyesno( title='Before you print!! ', message='are you sure you want to print this file with ' + printer_name) if mes == 0: print('Stopped printing!! ') if mes == 1: print('Printing... ') text = my_list.get(first=ANCHOR) if text: win32api.ShellExecute(0, 'print', text, None, '.', 0)
def compose(args): current_dir = get_workdir(args) with ChDir(current_dir): git_init(current_dir, GIT_REPO) git_pull(GIT_REPO) article_time = time.strftime('%Y-%m-%d', time.localtime()) if args.article_title: article_title = article_time + '-' + args.article_title else: article_title = article_time + '-untitled' subprocess.call('hugo new post/{0}.md'.format(article_title), shell=True) link_path = current_dir + '\\content\\post\\img' img_path = current_dir + '\\static\\img' article_path = current_dir + '\\content\\post\\' + article_title + '.md' subprocess.call('mklink /D {0} {1}'.format(link_path, img_path), shell=True) subprocess.call('pip install pywin32', shell=True) win32api.ShellExecute(0, 'open', article_path, '', '', 1)
def toolbar_icon_clicked(self, widget, movie): if not movie or not movie.trailer: return False use_shell = True command = self.get_config_value('command', self.preferences['command']['default']) if is_windows_system(): use_shell = False # Popen with shell=True doesn't work under windows with spaces in filenames if not command: import win32api log.debug('try ShellExecute with trailer %s' % movie.trailer) win32api.ShellExecute(0, None, movie.trailer, None, None, 0) return if '{1}' in command: command = command.replace('{1}', movie.trailer) else: # make a sequence results in Popen calls list2cmdline command = [command, movie.trailer] log.debug(command) Popen(command, shell=use_shell)
def startOrder(self, orderName, hwnd=0, op='open', params='', dir='', bShow=1): """ 根据指令,打开相应程序 :param orderName: 指令名 :param hwnd: 父窗口的句柄,如果没有父窗口,则为0。 :param op: 要进行的操作,为“open”、“print”或者为空。 :param params: 要运行的程序,或者打开的脚本。 :param dir: 要向程序传递的参数,如果打开的为文件,则为空。 :param bShow: 是否显示窗口。 :return: None """ file = self.get_order(orderName) if file != None: win32api.ShellExecute(hwnd, op, file, params, dir, bShow) self.tell('正在打开' + orderName) else: self.tell('没有找到对应的指令')
def outlook(self): ret = True try: win32api.ShellExecute(0,'open',r'C:\Program Files\Microsoft Office\Office14\OUTLOOK.EXE','','',1) time.sleep(5) outlook = win32.Dispatch('outlook.application') mail = outlook.CreateItem(0) mail.To = '*****@*****.**' mail.Subject = u'张秀昌发送的带附件的测试邮件' mail.Body = u'王宝强先生!恭喜您查收到该邮件' mail.HTMLBody = u'<h1 style="text-algin:center">王宝强先生!恭喜您查收到该邮件</h1><span style="color:red">详情如下:</span><br><img src="cid:zg">' #this field is optional # To attach a file to the email (optional): #attachment = 'menu.py' #mail.Attachments.Add(attachment) mail.Send() time.sleep(5) os.system("taskkill /F /IM OUTLOOK.EXE") print "OUTLOOK OK" return ret except Exception,e: print e print "OUTLOOK False" return False
class executor(object): def __init__(self, commandDict, openDict): self.mccLog = mccLog() self.commandDict = commandDict self.openDict = openDict def execute(self, commandList): self.mccLog.mccWriteLog(u'开始处理命令。') finishList = [] for each in commandList: innerCommand = each['innerCommand'] writeCommand = each['writeCommand'] if not innerCommand: self.exeWriteCommand(writeCommand) else: self.exeInnerCommand(innerCommand) self.exeWriteCommand(writeCommand) finishList.append(each['_id']) return finishList def exeInnerCommand(self, innerCommand): if innerCommand in self.commandDict: self.mccLog.mccWriteLog(u'执行命令') try: command = self.commandDict[innerCommand] os.system(command) self.mccLog.mccWriteLog(u'执行命令成功') except Exception, e: self.mccLog.mccError(u'执行命令失败' + str(e)) elif innerCommand in self.openDict: self.mccLog.mccWriteLog(u'打开文件') try: openFile = self.openDict[innerCommand] win32api.ShellExecute(0, 'open', openFile, '', '', 1) self.mccLog.mccWriteLog(u'打开文件成功') except Exception, e: self.mccLog.mccError(u'打开文件失败:' + str(e))
def onResOprMenu(self, evt): index = self._lstctlResults.GetNextItem(-1, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED) itemFileName = self._lstctlResults.GetItem(index, 0) itemFilePath = self._lstctlResults.GetItem(index, 1) filePath = itemFilePath.Text fileName = itemFileName.Text # 判断根目录的情况 if re.match(u'^\\w:\\\\$', filePath) or re.match(u'^/$', filePath): fullPath = filePath + fileName else: fullPath = filePath + unicode(os.path.sep) + fileName if sys.platform == 'win32': import win32api try: fullPath = fullPath.encode(KumquatRoot.LocalEncoding, u'ignore') filePath = filePath.encode(KumquatRoot.LocalEncoding, u'ignore') fileName = fileName.encode(KumquatRoot.LocalEncoding, u'ignore') except: pass if evt.Id == self.MENU_RESOPR_RUNFILE: try: win32api.ShellExecute(self.Handle, "open", fullPath, "", "", 1) except: win32api.WinExec('explorer "%s"' % fullPath) elif evt.Id == self.MENU_RESOPR_OPENDIR: win32api.WinExec('explorer /select, "%s"' % fullPath)
def daemonize(): ''' Daemonize a process ''' if 'os' in os.environ: if os.environ['os'].startswith('Windows'): import ctypes if ctypes.windll.shell32.IsUserAnAdmin() == 0: import win32api executablepath = sys.executable pypath = executablepath.split('\\') win32api.ShellExecute( 0, 'runas', executablepath, os.path.join(pypath[0], os.sep, pypath[1], 'Lib\\site-packages\\salt\\utils\\saltminionservice.py'), os.path.join(pypath[0], os.sep, pypath[1]), 0 ) sys.exit(0) else: import saltminionservice import win32serviceutil import win32service import winerror servicename = 'salt-minion' try: status = win32serviceutil.QueryServiceStatus(servicename) except win32service.error, details: if details[0]==winerror.ERROR_SERVICE_DOES_NOT_EXIST: saltminionservice.instart(saltminionservice.MinionService, servicename, 'Salt Minion') sys.exit(0) if status[1] == win32service.SERVICE_RUNNING: win32serviceutil.StopServiceWithDeps(servicename) win32serviceutil.StartService(servicename) else: win32serviceutil.StartService(servicename) sys.exit(0)
def screen(): time.sleep(8) # 避免已启动就打开屏保 while var == 1: hwnd = win32gui.GetForegroundWindow() app = win32gui.GetWindowText(hwnd) global dx, dy, dbutton, ddy, dkey pdx = dx pdy = dy pdbutton = dbutton pddy = ddy pdkey = dkey # 先将获取的输入状态存到一个局部变量 threadLock.acquire() dx = 0 dy = 0 dbutton = 0 ddy = 0 dkey = 0 threadLock.release() bi = 0 for i in applist: bi += app.find(i) print(bi + listlen) if bi + listlen == 0: #如果找到一个程序,那么bi+listlen应该不等于0 x1, y1 = pmouse.position # 此处获取鼠标坐标的目的是为了屏保启动后,将进程锁定在一个循环里,而不反复启动屏保 if pdx == 0 and pdy == 0 and pdbutton == 0 and pddy == 0 and pdkey == 0: win32api.ShellExecute(0, 'open', r'Mystify.scr', '', '', 1) print("show time") x2, y2 = pmouse.position while x1 == x2 and y1 == y2 and ddy == 0 and dbutton == 0 and dkey == 0: x2, y2 = pmouse.position # 加入dkey主要是解决只敲键盘退出屏保以后,无法退出while循环的问题 print("it's my show") time.sleep(dtime)
def OnExecuteExtension(self, extension): if extension.fileExt: doc = wx.GetApp().GetDocumentManager().GetCurrentDocument() if not doc: return if extension.opOnSelectedFile and isinstance( doc, project.ProjectEditor.ProjectDocument): filename = doc.GetFirstView().GetSelectedFile() if not filename: filename = doc.GetFilename() else: filename = doc.GetFilename() ext = os.path.splitext(filename)[1] if not '*' in extension.fileExt: if not ext or ext[1:] not in extension.fileExt: return cmds = [extension.command] if extension.commandPreArgs: cmds.append(extension.commandPreArgs) cmds.append(filename) if extension.commandPostArgs: cmds.append(extension.commandPostArgs) os.spawnv(os.P_NOWAIT, extension.command, cmds) else: cmd = extension.command if sysutilslib.isWindows(): import win32api win32api.ShellExecute( 0, "open", cmd, " " + extension.commandPreArgs + " " + extension.commandPostArgs, '', 1) else: if extension.commandPreArgs: cmd = cmd + ' ' + extension.commandPreArgs if extension.commandPostArgs: cmd = cmd + ' ' + extension.commandPostArgs subprocess.call(cmd, shell=True)
def open_waveQoE(self): #open waveQoE,wait for 3 seconds try: win32api.ShellExecute(0, 'open', WAVEQOE_EXE_PATH, '', '', 1) print "open waveQoE" time.sleep(3) except: print 'open waveQoE error' log_public(ERR_NO_0005) self.m_ERROR_MSG = ERR_NO_0005 return False #find handle for the waveQoE window hwnd2 = win32gui.FindWindow(WAVEQOE_CLASS, 'IxVeriwave WaveQoE Main Page') print 'hwnd2', hwnd2 #move window of 'IxVeriwave WaveQoE Main Page' to top left corner win32gui.MoveWindow(hwnd2, 0, 0, 626, 270, 1) time.sleep(0.5) #click button -- 'wired and wireless testing' self.myobj.Mouse_LB_D(str_app=WAVEQOE_CLASS, lb_dx='238', lb_dy='165', Flag='1') time.sleep(0.5) #click button -- 'wired only testing' #self.myobj.Mouse_LB_D(str_app='QWidget',lb_dx='426',lb_dy='166',Flag='1') #click button -- 'apply' self.myobj.Mouse_LB_D(str_app=WAVEQOE_CLASS, lb_dx='305', lb_dy='240', Flag='1') return True
def downloadVideo(self, address, quality, id): # 地址,品质,id # 请求页面 url = self.URL[address] + 'Index/invedio/id/' + id result = self.get(url.lower()) # 返回m3u8地址 m3u8 = self.getVideoValue(result, quality) m3u8text = self.get(m3u8) # 使用正则解析网址 tsUrl = self.TS_URL.findall(m3u8text) host = None if self.IS_HTTP.match(tsUrl[0]) != None: host = '' elif self.IS_SLASH.match(tsUrl[0]) != None: p = urllib.parse.urlparse(m3u8) host = p.scheme + '://' + p.netloc else: host = re.sub(self.M3U8_FILE_NAME, '', m3u8) pass # 使用正则替换网址 i = 0 j = len(tsUrl) while i < j: m3u8text = m3u8text.replace(tsUrl[i], host + tsUrl[i]) i += 1 # 写文件 title = '[录播]' + address + '_' + id + '_' + quality + '.' + time.strftime("%Y%m%d%H%M%S", time.localtime()) m3u8file = OUTPUT + title + '.m3u8' outfile = OUTPUT + title + '.mp4' file = open(m3u8file, 'w+') file.write(m3u8text) file.close() # 开启命令行下载 arg = '-protocol_whitelist file,http,https,tcp,tls -i "{m3u8}" -acodec copy -vcodec copy -f mp4 "{output}"'.format( m3u8=m3u8file, output=outfile, ) win32api.ShellExecute(0, 'open', FFMPEG, arg, '', True)
def login(): win32api.ShellExecute(0, 'open', 'D:\\EAS\eas\\client\\bin\\client.bat', '', '', 1) #win32api.ShellExecute(0, 'open', 'F:\\Documents\\Desktop\\qq\\11.txt', '', '', 1) tab = findx.matchImg( 'D:/myproject/EAS_auto/EASauto/chinese/login.png', 'D:/myproject/EAS_auto/EASauto/chinese/task_catch_simpletaget.png', 0.9) print(tab) pyautogui.FAILSAFE = True pyautogui.moveTo(300, 300, duration=0.25) pyautogui.PAUSE = 3.0 pyautogui.moveTo(300, 200, duration=0.25) pyautogui.size() # (1366, 768) width, height = pyautogui.size() print(width, height) pyautogui.moveTo(tab['result'][0], tab['result'][1] + 40, duration=0.25) pyautogui.click() pyautogui.typewrite('lshbiao') pyautogui.PAUSE = 0.3 pyautogui.press('shift') pyautogui.PAUSE = 0.3 pyautogui.press('tab') pyautogui.PAUSE = 1.0 pyautogui.typewrite('p@ssw0rd1') pyautogui.PAUSE = 0.3 pyautogui.press('enter') pyautogui.PAUSE = 1.5 pyautogui.moveTo(300, 500, duration=0.25) pyautogui.PAUSE = 1.5 pyautogui.press('enter') pyautogui.PAUSE = 1.5 pyautogui.moveTo(300, 600, duration=0.25) pyautogui.PAUSE = 1.5
def PrintAction(event=None): PRINTER_DEFAULTS = {"DesiredAccess": win32print.PRINTER_ALL_ACCESS} pHandle = win32print.OpenPrinter(_printer.get(), PRINTER_DEFAULTS) properties = win32print.GetPrinter(pHandle, 2) properties['pDevMode'].Color = 1 if str(_color.get()) == "Color" else 2 properties['pDevMode'].Copies = 1 win32print.SetPrinter(pHandle, 2, properties, 0) if not _filename: messagebox.showerror("Error", "No File Selected") return elif not _printer.get(): messagebox.showerror("Error", "No Printer Selected") return try: #win32print.SetDefaultPrinter(_printer.get()) win32api.ShellExecute(0, "print", _filename, None, ".", 0) win32print.ClosePrinter(pHandle) except: pass messagebox.showerror("Error", "There was an error printing the file :(")
def open_local_file(self, file_path: str, select: bool = False) -> None: # TODO: Move to utils.py """ Launch the local OS program on the given file / folder. :param file_path: The file URL to open. :param select: Hightlight the given file_path. Useful when opening a folder and to select a file. """ file_path = force_decode(file_path) log.debug("Launching editor on %r", file_path) if WINDOWS: if select: win32api.ShellExecute(None, "open", "explorer.exe", f"/select,{file_path}", None, 1) else: os.startfile(file_path) elif MAC: args = ["open"] if select: args += ["-R"] args += [file_path] subprocess.Popen(args) else: if select: # TODO NXDRIVE-848: Select feature not yet implemented # TODO See https://bugs.freedesktop.org/show_bug.cgi?id=49552 log.info( "The Select/Highlight feature is not yet implemented, please vote " "https://jira.nuxeo.com/browse/NXDRIVE-848 to show your interest" ) try: subprocess.Popen(["xdg-open", file_path]) except OSError: # xdg-open should be supported by recent Gnome, KDE, Xfce log.error("Failed to find and editor for: %r", file_path)
def run_service(): import win32api import time import win32service START_PENDING = win32service.SERVICE_START_PENDING or 2 RUNNING = win32service.SERVICE_RUNNING or 4 service_status = check_service_status(ZABBIX_WIN32_SERVICE_NAME) if service_status != START_PENDING or service_status != RUNNING: log.info('Start Zabbix Agent Service') try: win32api.ShellExecute(0, 'runas', 'sc', 'start \"%s\"' % ZABBIX_WIN32_SERVICE_NAME, '', 1) time.sleep(2) # it is not essential log.info('Zabbix Agent service started') except Exception as e: print e for item in list(e): if isinstance(item, str): print item.decode(DEFAULT_LOCALE_ENCODING), else: print item, raise RuntimeError else: log.info('Zabbix Agent service has already started, nothing to do')
def sacar_impresion(request,ubigeo, zonaq, seccq, aeut): lista =[] lista.append(str(ubigeo)+": " +str(zonaq) +", "+ str(seccq)+","+str(aeut) +"<br/>") #cond = Esp_Aeus.objects.filter(ubigeo=ubigeo, zona=zonaq, aeu_final=aeut) tempprinter = "\\\\172.18.1.35\\192.168.230.16" currentprinter = win32print.GetDefaultPrinter() secc = str(seccq).zfill(3) aeu_conv = str(aeut).zfill(3) #surce_file_name = "C:/Users/acarrillo/Desktop/pap.pdf" print ubigeo print zonaq print seccq print aeu_conv source_file_name = "\\\srv-fileserver\\CPV2017\\list_segm_esp\\"+str(ubigeo)+"\\"+str(zonaq)+"\\"+str(ubigeo)+str(zonaq)+str(secc)+str(aeu_conv)+".pdf" print source_file_name # \\\srv - fileserver\\CPV2017\\list_segm_esp\\" + str(ubigeo) + "\\" + zonal + "\\" + str(ubigeo) + zonal + str(secc) + str(aeu_conv) + ".pdf" win32print.SetDefaultPrinter(tempprinter) win32api.ShellExecute(0, "print", source_file_name, None, ".", 0) win32print.SetDefaultPrinter(currentprinter) return HttpResponse(lista) # # tempprinter = "\\\\server01\\printer01" # # tempprinter = "\\\\172.18.1.35\\192.168.230.68" # tempprinter = "\\\\172.18.1.35\\192.168.230.16" # currentprinter = win32print.GetDefaultPrinter() # source_file_name = "C:/Users/acarrillo/Desktop/pap.pdf" # win32print.SetDefaultPrinter(tempprinter) # win32api.ShellExecute(0, "print", source_file_name, None, ".", 0) # win32print.SetDefaultPrinter(currentprinter)
def cmd_open_with(ensoapi, application): """ Opens your currently selected file(s) or folder with the specified application """ seldict = ensoapi.get_selection() if seldict.get('files'): file = seldict['files'][0] elif seldict.get('text'): file = seldict['text'].strip() else: file = None if not (file and (os.path.isfile(file) or os.path.isdir(file))): ensoapi.display_message("No file or folder is selected") return displayMessage("Opening <command>%s</command>..." % application) #print file, application global shortcuts_map try: print(shortcuts_map[application][2]) print(shortcuts_map[application]) executable = expand_path_variables(shortcuts_map[application][2]) except: print(application) print(list(shortcuts_map.keys())) print(list(shortcuts_map.values())) try: rcode = win32api.ShellExecute( 0, 'open', executable, '"%s"' % file, os.path.dirname(file), win32con.SW_SHOWDEFAULT) except Exception as e: logging.error(e)
def cmd_open(ensoapi, target): """ Continue typing to open an application or document """ displayMessage(u"Opening <command>%s</command>..." % target) try: global shortcuts_map shortcut_type, shortuct_id, file_path = shortcuts_map[target] file_path = os.path.normpath(expand_path_variables(file_path)) logging.info("Executing '%s'" % file_path) if shortcut_type == SHORTCUT_TYPE_CONTROL_PANEL: if " " in file_path: executable = file_path[0:file_path.index(' ')] params = file_path[file_path.index(' ') + 1:] else: executable = file_path params = None try: rcode = win32api.ShellExecute(0, 'open', executable, params, None, win32con.SW_SHOWDEFAULT) except Exception, e: logging.error(e) else:
def work(self, item): # Download it. update_base = center.settings['update_link'] dir_name = tempfile.mkdtemp() updater = os.path.join(dir_name, 'knossos_updater.exe') progress.start_task(0, 0.98, 'Downloading update...') with open(updater, 'wb') as stream: util.download(update_base + '/updater.exe', stream) progress.finish_task() progress.update(0.99, 'Launching updater...') try: import win32api win32api.ShellExecute(0, 'open', updater, '/D=' + os.getcwd(), os.path.dirname(updater), 1) except: logging.exception('Failed to launch updater!') self.post(False) else: self.post(True) center.app.quit()
def compile(self): print "The automatic compile stopped working correct (September 2019)" print "Please start the Inno Compiler manually, IN ADMIN MODE" print "And run the script %s\\%s" % (thisDir, self.pathname) return try: import ctypes except ImportError: try: import win32api except ImportError: import os os.startfile(self.pathname) else: print "Ok, using win32api.", self.pathname win32api.ShellExecute(0, "compile", self.pathname, None, None, 0) else: print "Cool, you have ctypes installed." res = ctypes.windll.shell32.ShellExecuteA(0, "compile", self.pathname, None, None, 0) if res < 32: raise RuntimeError, "ShellExecute failed, error %d" % res
def print_file(filename, printer_name): win32api.ShellExecute(0, "print", path_prefix + '\\处理完成' + '\\' + filename, '/d:"%s"' % printer_name, ".", 0)