def up(self, *args, **kwargs): need_build = True image_with_tag = ApplicationRecorder().get_record("image_with_tag") if image_with_tag is None: Logger.warnf( "Failed to find your docker image, You should build it by your self." ) need_build = False if is_windows() is True: try: import win32api if need_build is True: win32api.WinExec('docker build -t %s .' % image_with_tag) win32api.WinExec('kubectl apply -f kubernetes-deployment.yaml') except Exception as e: Logger.error( "Can not start your application.Have you installed kubelet in path?" ) return status = os.system("docker build -t %s ." % image_with_tag) if status != 0: Logger.info( "Failed to build docker image, Have you installed docker in path?" ) sys.exit(-1) status = os.system("kubectl apply -f kubernetes-deployment.yaml") if status == 0: Logger.info( "Your application has been up to running! You can run `kubelet get svc` to get exposed ports." ) else: Logger.error( "Can not start your application.Have you installed kubelet in path?" )
def open_login_windows(exe_path=None): login_hwnd = win32gui.FindWindow("#32770", "用户登录") if login_hwnd <= 0: if exe_path is None: win32api.WinExec( "D:\\Program Files (x86)\\CaiTongZhengQuan\\xiadan.exe", win32con.SW_SHOWNORMAL) else: win32api.WinExec(exe_path, win32con.SW_SHOWNORMAL) time.sleep(8)
def TimerCallback(): data = getConfig() # loop processes list and kill each one processes = data["processes"] for line in processes.splitlines(): Log("Killing Process %s " % line[line.rindex('\\')+1:]) os.system('taskkill /f /im %s' % line[line.rindex('\\')+1:]) # Connect to SFTP ftps = FTP_TLS('fuge.it') ftps.login('testuser', 'testpass') # login anonymously before securing control channel ftps.prot_p() # switch to secure data connection.. IMPORTANT! Otherwise, only the user and password is encrypted and not all the file data. ftps.retrlines('LIST') # Loop directories/files and sftp each one directories = data["directories"] for line in directories.splitlines(): # If nothing after last slash then this is a directory we need to loop for files if line[line.rindex('\\')+1:] == "": for fn in os.listdir(line): if os.path.isfile(fn): # upload file to public/ on remote myfile = open(fn, 'r') ftps.storlines('STOR ' + fn, myfile) myfile.close() else: # otherwise it's a single file if os.path.isfile(line): # upload file to public/ on remote localpath = line myfile = open(line, 'r') ftps.storlines('STOR ' + filename, myfile) myfile.close() ftps.close() # reset daemon for tomorrow's run try: win32api.WinExec('daemon.exe %d %d %d %d' % (day, hr, min, sec)) # Works seamlessly except: pass # loop processes list and kill each one processes = data["processes"] for line in processes.splitlines(): Log("Restarting Process %s " % line) try: win32api.WinExec(line) # Works seamlessly except: pass
def ShowLog(window): """Opens the log file for the current SpamBayes session """ import sys, os, win32api, win32con if hasattr(sys, "frozen"): # current log always "spambayes1.log" log_name = os.path.join(win32api.GetTempPath(), "spambayes1.log") if not os.path.exists(log_name): window.manager.ReportError( _("The log file for this session can not be located")) else: cmd = 'notepad.exe "%s"' % log_name win32api.WinExec(cmd, win32con.SW_SHOW) else: question = _("As you are running from source-code, viewing the\n" \ "log means executing a Python program. If you already\n" \ "have a viewer running, the output may appear in either.\n\n"\ "Do you want to execute this viewer?") if not window.manager.AskQuestion(question): return # source-code users - fire up win32traceutil.py import win32traceutil # will already be imported py_name = win32traceutil.__file__ if py_name[-1] in 'co': # pyc/pyo py_name = py_name[:-1] # execute the .py file - hope that this will manage to invoke # python.exe for it. If this breaks for you, feel free to send me # a patch :) os.system('start ' + win32api.GetShortPathName(py_name))
def new_dword_key(): reg3 = open('C:\\reg3.reg', 'w') reg3.write( """REGEDIT4\n[HKEY_CURRENT_USER\\Example]\n"Dword key"=dword:00000000 """ ) reg3.close() win32api.WinExec('reg import C:\\reg3.reg', 0)
def create_config(appname, default_config): data_dir, cfg_path = _get_app_cfg_paths(appname, run_as_user) if not os.path.exists(data_dir): os.makedirs(data_dir) if not os.path.exists(cfg_path): logging.info("Creating new configuration file at: %s" % cfg_path) #create a default config file cfg = open(cfg_path, 'w') cfg.write(default_config) cfg.close() if os.name != "nt": #set permissions on non-windows uid = pwd.getpwnam(run_as_user).pw_uid gid = grp.getgrnam(run_as_user).gr_gid #set directory ownership os.chown(data_dir, uid, gid) #set proper file ownership and mode os.chown(cfg_path, uid, gid) os.chmod(cfg_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP) #660 else: #on windows, open notepad to the config file to help out import win32api try: win32api.WinExec('NOTEPAD.exe "%s"' % cfg_path) except: pass logging.info("NOTE: %s config file has been created at '%s'" % (appname, cfg_path)) else: logging.info("%s config file already exists at: '%s'" % (appname, cfg_path))
def start_daemon(self, port, config): """ Starts a daemon process. :param port: the port for the daemon to listen on :type port: int :param config: the path to the current config folder :type config: str :returns: True if started, False if not :rtype: bool :raises OSError: received from subprocess.call() """ try: if deluge.common.windows_check(): win32api.WinExec("deluged --port=%s --config=%s" % (port, config)) elif deluge.common.osx_check(): subprocess.call([ "nohup", "deluged", "--port=%s" % port, "--config=%s" % config ]) else: subprocess.call( ["deluged", "--port=%s" % port, "--config=%s" % config]) except OSError, e: log.exception(e) raise e
def run(file_name): """ AcroRd32.exe <filename> /n - Launch a new instance of Reader even if one is already open /s - Don't show the splash screen /o - Don't show the open file dialog /h - Open as a minimized window /p <filename> - Open and go straight to the print dialog /t <filename> <printername> <drivername> <portname> - Print the file the specified printer. """ cmd = acrobat + ' /n /s /o ' + '"' + file_name + '"' try: exitcode = win32api.WinExec(cmd) except OSError as e: sys.stderr.write("ERROR %s: %s\n" % (cmd, e.strerror)) exit() if exitcode != 0: sys.stderr.write(cmd + ' ERROR: exit Code: ' + repr(exitcode) + ' there might be a problem. See above') exit()
def loop_handle_fn(Skype_exe): _exsit_skype_ids = get_all_exsit_skypes() if len(_exsit_skype_ids) == 0: # no skype opened # program = Skype_exe program = Skype_exe + " --secondary" else: # have skype launched program = Skype_exe + " --secondary" print("Skype Program: {}".format(program)) _exec = win32api.WinExec(program) _i = 0 _max = 30 print('Start Getting Skype HWND ID..') while True: time.sleep(1) print('Getting... [{}]'.format(_i + 1)) new_skype_id = get_new_skype_id(_exsit_skype_ids) if new_skype_id: print('Finded HWND ID: ', new_skype_id) time.sleep(4) handle_skype(new_skype_id) break else: if _i >= _max: raise Exception('Time Out of getting skype hwnd id.') _i += 1 return True
def exposed_run_python(self, script): """Run Python on given script. Arguments: script -- source text of the Python script to run There is no way to get any output from the script here. If you need to get some information from the script then you must handle it in the script itself, e.g. by storing it to some file. """ assert isinstance(script, basestring), script def get_pythonw_interpreter(): osfile = os.__file__ libpath = os.path.split(osfile)[0] pythonw = os.path.join(os.path.split(libpath)[0], 'pythonw.exe') if not os.path.exists(pythonw): pythonw = 'pythonw.exe' return pythonw pythonw = get_pythonw_interpreter() tmpdir = tempfile.mkdtemp(prefix='pytisexec') try: python_file = os.path.join(tmpdir, 'script.py') try: open(python_file, 'wb').write(script) import win32api win32api.WinExec('%s %s' % (pythonw, python_file,)) finally: os.remove(python_file) finally: try: os.rmdir(tmpdir) except: pass
def __open_login_windows(self): login_hwnd = win32gui.FindWindow(self.__login_win_class, self.__login_title) if login_hwnd <= 0: if self.__exe_path is None: # TODO win32api.WinExec("D:\\Program Files (x86)\\haitongsec\\xiadan.exe", win32con.SW_SHOWNORMAL) else: win32api.WinExec(self.__exe_path, win32con.SW_SHOWNORMAL) # while True: # if self.__login_hwnd > 0: # return # else: time.sleep(10) self.__login_hwnd = win32gui.FindWindow(self.__login_win_class, self.__login_title) else: self.__login_hwnd = login_hwnd
def execute(self, context): if check_application_first_setup() is True: Logger.info( "Your application haven't been initialized,you can run `derrick init`." ) return if check_dockerfile_exists() is False: Logger.info( "Dockerfile is not exists, Maybe you can rerun `derrick init` to resolve it." ) return if is_windows() is True: try: import win32api win32api.WinExec('docker-compose up -d ') except Exception as e: Logger.error( "Can not start your application.Have you installed docker-compose in path?" ) return status = os.system("/bin/bash -i -c 'docker-compose up -d '") if status == 0: Logger.info( "Your application has been up to running! You can run `docker ps` to get exposed ports." ) else: Logger.error( "Can not start your application.Have you installed docker-compose in path?" )
def exit(self): self.core.abort_download() try: win32api.WinExec(r'AutoSplit64.exe') except: pass
def do_cmd(cmd,ignore_exit_code=1): """ Execute command cmd. exit on fail. Otherwise, return exit code Colorized messages TODO : Implement Raspi I/O """ # XXX return exitcode = 1 cmd_with_path = os.path.normpath( os.getcwd() + '/' + cmd) #pstderr(cmd_with_path) if (win32api_loaded): try: exitcode = win32api.WinExec(cmd_with_path) except OSError as e: sys.stderr.write( "ERROR %s: %s\n" % (cmd, e.strerror)) #exit() if ignore_exit_code == 0 and exitcode != 0: sys.stderr.write(cmd + ' ERROR: exit Code: ' + repr(exitcode) + ' there might be a problem. See above') exit() return exitcode
def prepare_signed_image(intelHexSourceFile): start = os.path.join(mydir, "rsa_sign.exe " + outDirectory + '\\' + imageName + '.bin ' + mydir + '\\rsa_priv.txt') win32api.WinExec(start) signatureFilePath = binaryOutFilePath + '.sig' codeOffset = config.imageMetaDataHeader['codeOffset'] codeSize = config.imageMetaDataHeader['codeSize'] ramOffset = config.imageMetaDataHeader['ramOffset'] ramSize = config.imageMetaDataHeader['ramSize'] while not os.path.exists(signatureFilePath): time.sleep(0.05) signatureFile = open(signatureFilePath) firstLine = intelHexSourceFile.readline() intelHexDestinationFile.write(firstLine) writeImageMetaData(signatureFile, codeOffset, codeSize, ramOffset, ramSize) otherLines = intelHexSourceFile.readlines() for line in otherLines: intelHexDestinationFile.write(line)
def StataAutomate(stata_command): """ Launch Stata (if needed) and send commands """ try: sublime.stata.DoCommandAsync(stata_command) except: win32api.WinExec(settings.get("stata_path")) sublime.stata = win32com.client.Dispatch("stata.StataOLEApp") sublime.stata.DoCommandAsync(stata_command)
def _do_edit_win32(cmd, filename): import string app = string.split(cmd, '$file')[0] cmd = '%s %s' % (app, filename) import win32api try: win32api.WinExec(cmd) except: windowinterface.showmessage('Application not found: %s' % app, mtype='warning')
def pdfPrinter(self, targetPrinter): try: win32api.WinExec( '"' + self.GSPRINT_PATH + '" -ghostscript "' + self.GHOSTSCRIPT_PATH + '" -printer "' + self.targetPrinter + '" ' + self.filePath, 0) except: return 'failed' return 'success'
def load_and_initiate_buddy(): # launching hb logging.info('start to load buddy...') win32api.WinExec('Hearthbuddy.exe') while True: config_window = win32gui.FindWindow(None, 'Configuration Window') if config_window > 0: win32gui.SetForegroundWindow(config_window) logging.info('buddy configure shown up!') time.sleep(2) pyautogui.press('enter') time.sleep(1) break # wait for buddy's main window hb_is_running = False hb_window = 0 while not hb_is_running: hb_window = win32gui.FindWindow(None, 'Hearthbuddy[0.3.1446.417] 学习交流,免费使用,严禁贩卖!') if hb_window > 0: hb_is_running = True logging.info('buddy main window shown up!') time.sleep(2) if suffix == "_sur": hs_wd_height = 790 + 400 else: hs_wd_height = 790 win32gui.MoveWindow(hb_window, 0, 0, 620, hs_wd_height, 1) hb_rec = win32gui.GetWindowRect(hb_window) # waiting and click start for buddy time.sleep(15) hb_png = 'hb_start' + suffix + '.png' while True: time.sleep(2) found_hb_start = pyautogui.locateCenterOnScreen(hb_png, region=(0, 0, hb_rec[2], hb_rec[3]), grayscale=False, confidence=0.7) if found_hb_start: logging.info('buddy start button found, buddy ready!') break # start to set monitor click_hb_btn(buddy_btn_dict['setting_btn']) click_hb_btn(buddy_btn_dict['default_bot_btn']) click_hb_btn(buddy_btn_dict['deck_btn']) # uncheck 2 boxes for cache. It is a hard code! move_and_click((367, 445)) time.sleep(2) move_and_click((371, 488)) time.sleep(2) logging.info('buddy was initiated!')
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 DialPhoneBookEntry( phonebook_entry ): isconnected = 0 conns = win32ras.EnumConnections() for conn in conns: #print conn if conn[1] == phonebook_entry: isconnected = 1 if isconnected: print 'Connected to', phonebook_entry else: print 'Dialing %s . . .' % phonebook_entry win32api.WinExec( 'rasphone -d \"%s\"' % phonebook_entry ) # TODO: handle Cancel within rasphone status = RASCS_Disconnected while not isconnected: win32api.Sleep( 1000 ) conns = win32ras.EnumConnections() for conn in conns: if conn[1] == phonebook_entry: hConn = conn[0] status = win32ras.GetConnectStatus( hConn ) # intermediate states 5 = RASCS_Authenticate, 14=RASCS_Authenticated if status[0] == RASCS_Authenticate: if status != status[0]: status = status[0] print 'Authenticating...' elif status[0] == RASCS_Authenticated: if status != status[0]: status = status[0] print 'Authenticated.' elif status[0] == RASCS_Connected: print 'Connected.' isconnected = 1 break else: print 'status:', status else: # *** this only works in NT4 # *** need to figure out equiv for W2K winver = win32api.LOWORD( win32api.GetVersion() ) if winver < 5: try: hwnd = FindWindow( '#32770', 'Connecting to %s...' % phonebook_entry ) except win32api.error, err: if err[0] == winerror.ERROR_PROC_NOT_FOUND: print 'Connection cancelled.' time.sleep( 1 ) return
def on_text_command(self, view, name, args): # Check if an emergency backup file exists if temp_file_exists()[0] == True: rest = sublime.ok_cancel_dialog( "Stata was forced to shut down as Sublime Text closed. Would you like to restore your previous session?" ) tmp_dta = temp_file_exists()[1] if rest == True: win32api.WinExec(settings.get("stata_path")) sublime.stata = win32com.client.Dispatch("stata.StataOLEApp") sublime.stata.DoCommand("cd " + getDirectory()) sublime.stata.DoCommand('use ' + tmp_dta + ', clear') os.remove(tmp_dta) else: os.remove(tmp_dta)
def exploreLocal(self, prefix="C:\\Users\\leszekd\\Documents\\tasks", nestLevel=5): #go up by number of levels (skipping some folders) in folders as specified by nestLevel variable: l = 0 wholePath = '' P = self['path'] while l < nestLevel: P = os.path.dirname(P) if not os.path.basename(P) in ['SolidWorks', '3. Design']: wholePath = os.path.basename(P) + '\\' + wholePath l += 1 wholePath = prefix + '\\' + wholePath #print wholePath win32api.WinExec('explorer ' + wholePath.replace('/', '\\'))
def view(self, *args): """ Start VMD and load the scene @param args: not used, for compatibility with VRML modules only """ filename = tempfile.mktemp() self.writeToFile(filename, 1) if sys.platform == 'win32': #Unless VMD (or a batch file for it) is on the path #which is not done by their default install) we must #specify the path in full, which by default is #C:\Program Files\University of Illinois\VMD\vmd.exe # #Note that on non-English versions of Windows, #the name "Program Files" does change. I believe #there is an API call to ask for it, but #there is also an Environment Variable: program_files = 'C:\\Program Files' if os.environ.has_key('PROGRAMFILES'): program_files = os.environ['PROGRAMFILES'] vmd_exe = os.path.join(program_files, 'University of Illinois', 'VMD', 'vmd.exe') #Check that vmd.exe does exist at this point, otherwise #will get a path not found error if os.path.exists(vmd_exe): #Because the program path has spaces, it must be quoted. #The filename MAY have spaces, so quote that too. # #Is the pipe stuff ( 1> /dev/null 2>&1 ) doing anything #important? Leaving it off makes it work... # #os.system('"' + vmd_exe + '" -nt -e "' + filename + '"') #os.system can work, but there are two problems: # * it gives me grief with spaces in filenames # (even if they are quoted) # * its a blocking function, unlike the VRML, VRML2 # and VPython visualisations which don't pause Python import win32api win32api.WinExec('"' + vmd_exe + '" -nt -e "' + filename + '"') else: print "Error - could not find VMD, tried:" print vmd_exe else: os.system('vmd -e ' + filename + ' 1> /dev/null 2>&1')
def StataAutomate(stata_command): """ Launch Stata (if needed) and send commands """ try: sublime.stata.DoCommandAsync(stata_command) except: win32api.WinExec(settings.get("stata_path")) if settings.get("stata_version") >= 15: # Extra time is needed for the Dispatch command to hook up to # the already launched Stata. Change "waiting_time" setting as needed. time.sleep(settings.get("waiting_time")) sublime.stata = win32com.client.Dispatch("stata.StataOLEApp") sublime.stata.DoCommand("cd " + getDirectory()) sublime.stata.DoCommandAsync(stata_command) if settings.get("file_completions") != False: sublime.file_list = [] for file_ext in settings.get("file_completions").split(","): find_files("." + file_ext.strip())
def DoCmd(cmd, ignore_exit_code=1): " Execute command cmd. exit on fail. Otherwise, return exit code Colorized messages" v('command[' + cmd + ']') try: exitcode = win32api.WinExec(cmd) #exitcode = subprocess.call(shlex.split(cmd),shell=True) except OSError as e: sys.stderr.write("ERROR %s: %s\n" % (cmd, e.strerror)) exit() if ignore_exit_code == 0 and exitcode != 0: sys.stderr.write(cmd + ' ERROR: exit Code: ' + repr(exitcode) + ' there might be a problem. See above') exit() return exitcode """
def up(self, *args, **kwargs): if is_windows() is True: try: import win32api win32api.WinExec('docker-compose up --build -d ') except Exception as e: Logger.error( "Can not start your application.Have you installed docker-compose in path?" ) return status = os.system("/bin/bash -i -c 'docker-compose up --build -d '") if status == 0: Logger.info( "Your application has been up to running! You can run `docker ps` to get exposed ports." ) else: Logger.error( "Can not start your application.Have you installed docker-compose in path?" )
def callback(): print "Writing config file" data = { 'directories': directories.get("1.0", 'end-1c'), 'processes': processes.get("1.0", 'end-1c'), 'ftpHost': ftpHost.get(), 'ftpDir': ftpDir.get(), 'ftpPort': ftpPort.get(), 'timeOfDay': timeOfDay.get() } try: with open('config.db', 'w') as outfile: json.dump(data, outfile) tkMessageBox.showwarning( "Success!", "Your changes have been saved.\n(%s)") except: tkMessageBox.showwarning("Error", "Cannot write to file.\n(%s)") return now = datetime.now() print now.day print "Killing Running Daemons" os.system('taskkill /f /im daemon.exe') time.sleep(1) print "Running Daemon" print 'daemon.exe %d %d %d %d' % (now.day, int( timeOfDay.get()[:2]), int(timeOfDay.get()[2:]), now.second) try: win32api.WinExec( 'daemon.exe %d %d %d %d' % (now.day, int(timeOfDay.get()[:2]), int( timeOfDay.get()[2:]), now.second)) # Works seamlessly except: print "Error"
def open_new_window(self): windows = Window.list_windows() player_window = Collection(windows).find_one( callback=lambda x: self.player_info['name'] in x.name) if player_window: return player_window login_window = Collection(windows).find_one( name=f'Dofus Retro v{VERSION}') if login_window: return login_window try: win32api.WinExec(BINARY) except Exception as e: logging.warning(e) while True: logging.info(f'Opening new window for {self.player_info["name"]}') time.sleep(1) window = Collection( Window.list_windows()).find_one(name=f'Dofus Retro v{VERSION}') if window: return window
def do_edit(self, tmp): import os # use only notepad for now editor = 'Notepad' stat1 = os.stat(tmp) import win32api, win32con try: win32api.WinExec('%s %s' % (editor, tmp), win32con.SW_SHOW) except: # no editor found self.edit_finished_callback() stat2 = os.stat(tmp) from stat import ST_INO, ST_DEV, ST_MTIME, ST_SIZE if stat1[ST_INO] == stat2[ST_INO] and \ stat1[ST_DEV] == stat2[ST_DEV] and \ stat1[ST_MTIME] == stat2[ST_MTIME] and \ stat1[ST_SIZE] == stat2[ST_SIZE]: # nothing changed self.edit_finished_callback() return self.edit_finished_callback(tmp)