def rip(driveLetter, movieName): out = Path.Combine(Path.GetTempPath(), movieName) # for debugging if True: return Directory.GetFiles(out)[0] print("Saving to: '%s'" % out) if not os.path.exists(out): os.makedirs(out) p = Process() p.StartInfo.UseShellExecute = False #p.StartInfo.RedirectStandardOutput = True p.StartInfo.FileName = "makemkvcon" p.StartInfo.Arguments = '--minlength=2700 mkv disc:0 all "%s"' % out print("Saving to: '%s'" % out) print(p.StartInfo.Arguments) if p.Start(): print("Ripping") p.WaitForExit() if p.ExitCode == 0: print("Successfully ripped %s" % movieName) return Directory.GetFiles(out)[0] else: print("Error: %d" % p.ExitCode) else: print("Error ripping, quitting")
def ShellExecute(ShellCommand, Path="C:\\WINDOWS\\System32\\", Username=None, Domain=None, Password=None): ShellCommandName = ShellCommand.split()[0] ShellCommandArguments = ' '.join(ShellCommand.split()[1:]) print "[*] Path: {} Command: {} Args: {}".format(Path, ShellCommandName, ShellCommandArguments) shellProcess = Process() if Username and Domain and Password: print "[*] Running command as {}\\{}:{}".format(Domain, Username, Password) shellProcess.StartInfo.UserName = Username shellProcess.StartInfo.Domain = Domain SecurePassword = SecureString() for c in Password: SecurePassword.AppendChar(c) shellProcess.StartInfo.Password = SecurePassword shellProcess.StartInfo.FileName = ShellCommandName shellProcess.StartInfo.Arguments = ShellCommandArguments shellProcess.StartInfo.WorkingDirectory = Path shellProcess.StartInfo.UseShellExecute = False shellProcess.StartInfo.CreateNoWindow = True shellProcess.StartInfo.RedirectStandardOutput = True shellProcess.Start() output = shellProcess.StandardOutput.ReadToEnd() shellProcess.WaitForExit() return output
def sendGameCommand(inputString): #log("Python is located at: " + pythonPath + " and script is " + scriptPath) #log("running external process...") p = Process() p.StartInfo.FileName = pythonPath # oh my gosh why does the chatbot folder have a space in it pArgs = "" pArgs = pArgs + "\"" + scriptPath + "\"" + " " + str( settings[Settings_UseDelays]) pArgs = pArgs + " " + settings[Settings_BufferDelay] + " " + settings[ Settings_HoldDelay] + " " + settings[Settings_PressDelay] pArgs = pArgs + " " + str(settings[Settings_UseFnKeys]) + " " + inputString p.StartInfo.Arguments = pArgs #log(pArgs) p.StartInfo.RedirectStandardError = True p.StartInfo.UseShellExecute = False p.StartInfo.CreateNoWindow = True p.Start() #log("process started: " + p.StartInfo.FileName + p.StartInfo.Arguments) p.WaitForExit() #log("process exited with " + str(p.ExitCode)) pErrors = p.StandardError.ReadToEnd() if len(pErrors) > 0: log(p.StandardError.ReadToEnd()) return
def openCustomCommandWithList(self, dirList): if not self.settings.get("enableCustomCommand") or self.settings.get("customArgs") == "": self.dbg("Custom commands are disabled or custom args are empty. Skipping trying to open with @list@. "+self.settings.get("customArgs")) return False if not System.IO.File.Exists(self.settings.get("customExec")): MessageBox.Show(lang.enUs("customCommandNotFound")+"\n\n\""+self.settings.get("customExec")+"\"", lang.enUs("windowTitle")+" "+lang.enUs("error"), MessageBoxButtons.OK, MessageBoxIcon.Error) # We want to halt, so we pretend we did something. return True if self.settings.get("customArgs").find("@list@") > -1: parsedCommand = self.buildOpenerCommand() listLen = len(dirList) maxWin = self.settings.get("maxWindows") if maxWin > 0 and listLen > maxWin: self.dbg("Using "+str(maxWin)+" of "+str(listLen)+" directories for a single command") dirPile = '"'+'" "'.join(dirList[0:maxWin])+'"' else: self.dbg("Using "+str(listLen)+" directories for a single command") dirPile = '"'+'" "'.join(dirList)+'"' parsedArgs = self.settings.get("customArgs").replace("@list@", dirPile) try: self.dbg("Running \""+parsedCommand+"\" "+parsedArgs) Process.Start(parsedCommand, parsedArgs) except: errType, errValue, errTrace = sys.exc_info() MessageBox.Show(lang.enUs("failedCommand")+"\n\n"+parsedCommand+" "+parsedArgs+"\n\n"+str(errValue), lang.enUs("windowTitle"), MessageBoxButtons.OK, MessageBoxIcon.Warning) return True return False
def popen(executable, arguments): global process # XXX: keep it alive processStartInfo = ProcessStartInfo(executable, arguments) processStartInfo.UseShellExecute = False processStartInfo.CreateNoWindow = True processStartInfo.RedirectStandardOutput = True process = Process.Start(processStartInfo) return file(process.StandardOutput.BaseStream, "r")
def run_cmd(command): # os.system(command) pinfo = ProcessStartInfo() pinfo.FileName = "cmd.exe" pinfo.WindowStyle = ProcessWindowStyle.Hidden pinfo.Arguments = "/C" + command cmd = Process.Start(pinfo) cmd.WaitForExit()
def start_imaging(path): psInfo = ProcessStartInfo() psInfo.FileName = path + "Imaging.exe" psInfo.Arguments = "Rowthon 1" psInfo.CreateNoWindow = False psInfo.UseShellExecute = False psInfo.RedirectStandardOutput = True p = Process.Start(psInfo)
def LaunchGnuplot(gnuplotPath, scriptPath, fontPath): proc = Process() proc.StartInfo.FileName = gnuplotPath proc.StartInfo.Arguments = '"%s"' % scriptPath proc.StartInfo.EnvironmentVariables['GDFONTPATH'] = fontPath proc.StartInfo.EnvironmentVariables['GNUPLOT_FONTPATH'] = fontPath proc.StartInfo.UseShellExecute = False proc.Start() proc.WaitForExit()
def ExitApp(): from System.Diagnostics import Process p = Process() p.StartInfo.UseShellExecute = False p.StartInfo.RedirectStandardOutput = True p.StartInfo.FileName = 'TASKKILL' p.StartInfo.Arguments = '/IM logiccircuit.exe' p.Start() p.WaitForExit()
def StartRevitProcess(revitVersion, initEnvironmentVariables): revitExecutableFilePath = RevitVersion.GetRevitExecutableFilePath(revitVersion) psi = ProcessStartInfo(revitExecutableFilePath) psi.UseShellExecute = False psi.RedirectStandardError = True psi.RedirectStandardOutput = True psi.WorkingDirectory = RevitVersion.GetRevitExecutableFolderPath(revitVersion) initEnvironmentVariables(psi.EnvironmentVariables) revitProcess = Process.Start(psi) return revitProcess
def run_tool(toolname, params): # run the external tool app = Process() app.StartInfo.FileName = toolname app.StartInfo.Arguments = params app.Start() done = app.WaitForExit() return done
def generate(exe, mod_name): proc = Process() proc.StartInfo.FileName = exe proc.StartInfo.Arguments = "logmodule.py " + mod_name proc.StartInfo.UseShellExecute = False proc.StartInfo.RedirectStandardOutput = True if not proc.Start(): raise Exception("process failed to start") return proc.StandardOutput.ReadToEnd()
def func(self, idict=None, **kwargs): if not idict: idict = {} idict.update(kwargs) with open(self.ipath, 'wb+') as fh: json.dump(idict, fh) with open(self.opath, 'wb+') as fh: fh.write('') p = Process() p.StartInfo.UseShellExecute = False p.StartInfo.RedirectStandardOutput = True p.StartInfo.RedirectStandardError = True p.StartInfo.FileName = self.python p.StartInfo.Arguments = '-u {0} {1} {2}'.format( self.script, self.ipath, self.opath) p.Start() p.WaitForExit() while True: # combine with updatefunc? # into userfunc? if self.waitfunc: self.waitfunc() line = p.StandardOutput.ReadLine() if not line: break line = line.strip() print(line) # check if this does what it is supposed to do if self.updatefunc: self.updatefunc(self.updateconduit, line) stderr = p.StandardError.ReadToEnd() if stderr: self.error = stderr raise ScriptServerError(stderr) print(p.StandardOutput.ReadToEnd()) print(p.ExitCode) with open(self.opath, 'rb') as fh: result = json.load(fh) if not result: self.error = 'No output was generated.' raise ScriptServerError(self.error) self.error = result.get('error', None) if self.error: raise ScriptServerError(self.error) self.data = result.get('data', None) self.profile = result.get('profile', '') self.iterations = result.get('iterations', []) return self.data
def _xecute(self, *args, **kwargs): """Execute a function with optional positional and named arguments. """ idict = {'args': args, 'kwargs': kwargs} with open(self.ipath, 'w+') as fh: json.dump(idict, fh, cls=DataEncoder) with open(self.opath, 'w+') as fh: fh.write('') p = Process() p.StartInfo.UseShellExecute = False p.StartInfo.RedirectStandardOutput = True p.StartInfo.RedirectStandardError = True p.StartInfo.FileName = self.python p.StartInfo.Arguments = '-u -c "{0}" {1} {2} {3} {4}'.format( WRAPPER, self.basedir, self.funcname, self.ipath, self.opath) p.Start() p.WaitForExit() while True: line = p.StandardOutput.ReadLine() if not line: break line = line.strip() if self.verbose: print(line) stderr = p.StandardError.ReadToEnd() print(stderr) with open(self.opath, 'r') as fh: odict = json.load(fh, cls=DataDecoder) self.data = odict['data'] self.profile = odict['profile'] self.error = odict['error'] if self.delete_files: try: os.remove(self.ipath) except OSError: pass try: os.remove(self.opath) except OSError: pass if self.error: raise Exception(self.error) return self.data
def openDirWithCommand(self, dirPath, noWarnings): if self.openCustomCommandWithList(self.dirList): return; parsedCommand = self.buildOpenerCommand() parsedArgs = self.buildSingleCommandArgs(dirPath) try: self.dbg("Running \""+parsedCommand+"\" "+parsedArgs) Process.Start(parsedCommand, parsedArgs) except: errType, errValue, errTrace = sys.exc_info() MessageBox.Show(lang.enUs("failedCommand")+"\n\n"+parsedCommand+" "+parsedArgs+"\n\n"+str(errValue), lang.enUs("windowTitle"), MessageBoxButtons.OK, MessageBoxIcon.Warning)
def Popen(CMD, *a, **b): ''' CMD is a list - a command and its arguments ''' p = Process() p.StartInfo.UseShellExecute = False p.StartInfo.RedirectStandardInput = True p.StartInfo.RedirectStandardOutput = True p.StartInfo.RedirectStandardError = True p.StartInfo.FileName = CMD[0] p.StartInfo.Arguments = ' '.join(CMD[1:]) p.Start() return(p)
def transcode(mkvFile, movieName): p = Process() p.StartInfo.UseShellExecute = False #p.StartInfo.RedirectStandardOutput = True p.StartInfo.FileName = "HandBrakeCLI" p.StartInfo.Arguments = '-i "%s" -o %s.mp4 -f mp4 -e x264' % (mkvFile, movieName) if p.Start(): print("Transcoding") p.WaitForExit() if p.ExitCode == 0: print("Successfully transcoded %s" % movieName) else: print("Error: %d" % p.ExitCode) else: print("Error transcoding, quitting")
def StartCmdProcess(commandLine): # NOTE: do not call Process.WaitForExit() until redirected streams have been entirely read from / closed. # doing so can lead to a deadlock when the child process is waiting on being able to write to output / error # stream and the parent process is waiting for the child to exit! See Microsoft's documentation for more info. # NOTE: if redirecting both output and error streams, one should be read asynchronously to avoid a deadlock where # the child process is waiting to write to one of the streams and the parent is waiting for data from the other # stream. See Microsoft's documentation for more info. psi = ProcessStartInfo('cmd.exe', '/U /S /C " ' + commandLine + ' "') psi.UseShellExecute = False psi.CreateNoWindow = True psi.RedirectStandardInput = False psi.RedirectStandardError = False # See notes above if enabling this alongside redirect output stream. psi.RedirectStandardOutput = True psi.StandardOutputEncoding = Encoding.Unicode p = Process.Start(psi) return p
def Start_Button_Click(self, sender, e): self.Port = self.Port_TextBox.Text self.IPaddress = self.IPaddress_TextBox.Text if self.JoystickEnable_CheckBox.IsEnabled == True: self.Joystick = 'y' if self.JoystickEnable_CheckBox.IsChecked == False: self.Joystick = 'n' if self.DebugEnabled_CheckBox.IsChecked == True: self.Debug = 'y' if self.DebugEnabled_CheckBox.IsChecked == False: self.Debug = 'n' if self.TCPEnabled_CheckBox.IsChecked == True: self.TCP = 'y' if self.TCPEnabled_CheckBox.IsChecked == False: self.TCP = 'n' self.file = open('details.txt', 'w') self.file.write(self.Port+'\n'+self.IPaddress+'\n'+self.CMDrobot+'\n'+self.TCP+'\n'+self.Joystick+'\n'+self.Debug+'\n') self.file.close() Process.Start('python.exe', 'ControlModuleBeta1.6.6.py')
def run_command(args, input=None, verbose=False): """ Run stuff on commandline. """ # credit for this is due here: # http://www.ironpython.info/index.php/Launching_Sub-Processes p = Process() have_stdin = input is not None p.StartInfo.UseShellExecute = False p.StartInfo.RedirectStandardInput = have_stdin p.StartInfo.RedirectStandardOutput = True p.StartInfo.RedirectStandardError = True p.StartInfo.FileName = args[0] # not a precise way to join these! See list2cmdline in CPython's subprocess.py for the proper way. cmd = ' '.join([str(a) for a in args[1:]]) p.StartInfo.Arguments = cmd p.Start() if have_stdin: p.StandardInput.Write(input) if verbose: while not p.HasExited: p.Refresh() print print "%s -" % p.ToString() print "-----------------------" print " physical memory usage: %s" % p.WorkingSet64 print " base priority: %s" % p.BasePriority print " user processor time: %s" % p.UserProcessorTime print " privileged processor time: %s" % p.PrivilegedProcessorTime print " total processor time: %s" % p.TotalProcessorTime if p.Responding: print "Status = Running" else: print "Status = Not Responding" stdout = p.StandardOutput.ReadToEnd() stderr = p.StandardError.ReadToEnd() p.WaitForExit() return stdout, stderr, p.ExitCode
def runCode(self, code, interpreter="ipy.exe", insert_args=''): if interpreter == "ipy.exe": code = self.TEMPLATE % code self.write("test-code.py", code) process = Process() process.StartInfo.FileName = interpreter process.StartInfo.Arguments = "%s test-code.py" % insert_args process.StartInfo.WorkingDirectory = self.testDir process.StartInfo.UseShellExecute = False process.StartInfo.RedirectStandardOutput = process.StartInfo.RedirectStandardError = True process.Start() process.WaitForExit(600000) if not process.HasExited: process.Kill() output = process.StandardOutput.ReadToEnd() error = process.StandardError.ReadToEnd() return process.ExitCode, output, error
def run_command(self, args, input=None): from System.Diagnostics import Process p = Process() have_stdin = input is not None p.StartInfo.UseShellExecute = False p.StartInfo.RedirectStandardInput = have_stdin p.StartInfo.RedirectStandardOutput = True p.StartInfo.RedirectStandardError = True p.StartInfo.CreateNoWindow = True p.StartInfo.FileName = args[0] # not a precise way to join these! See list2cmdline in CPython's subprocess.py for the proper way. p.StartInfo.Arguments = " ".join(args[1:]) App.log(" Running command: " + " ".join(args)) p.Start() if have_stdin: p.StandardInput.Write(input) p.WaitForExit() stdout = p.StandardOutput.ReadToEnd() stderr = p.StandardError.ReadToEnd() return stdout, stderr, p.ExitCode
class Popen(object): def __init__(self, args, executable, stdin=None, stdout=None, stderr=None): self.p = Process() i = self.p.StartInfo i.UseShellExecute = False i.RedirectStandardInput = True i.RedirectStandardOutput = True i.RedirectStandardError = True i.FileName = executable args.pop(0) i.Arguments = " ".join(args) def communicate(self, stdinData=None): self.p.Start() stdin = self.p.StandardInput stdout = self.p.StandardOutput stderr = self.p.StandardError if stdinData is not None: stdin.AutoFlush = True stdin.Write(stdinData) stdin.Flush() # ? problem when we have input data only! stdoutData = stdout.ReadToEnd() stderrData = stderr.ReadToEnd() if not self.p.HasExited: self.p.Kill() stdin.Close() stdout.Close() stderr.Close() self.p.Close() return stdoutData, stderrData
# parameters should be created # crossTable, The CrossTablePlot Visualization import clr clr.AddReference("System.IO") from Spotfire.Dxp.Application.Visuals import CrossTablePlot from System.IO import TextWriter, File from System.Diagnostics import Process ct = crossTable.As[CrossTablePlot]() textWriter = File.CreateText("D:\\SSOTEMP\\" + SessionID) ct.ExportText(textWriter) textWriter.Close() p = Process() p.StartInfo.FileName = ToolPath p.StartInfo.UseShellExecute = False p.StartInfo.RedirectStandardInput = True p.StartInfo.RedirectStandardOutput = True p.StartInfo.RedirectStandardError = True p.StartInfo.CreateNoWindow = True p.StartInfo.Arguments = SessionID + " CROSSTABLE" + " txt" p.Start()
class IronPythonInstance: """ Class to hold a single instance of the Iron Python interactive console for testing purposes, and direct input to and from the instance. Example usage: from sys import exec_prefix ip = IronPythonInstance(sys.executable, exec_prefix) AreEqual(ip.Start(), True) if ip.ExecuteLine("1+1") != "2": raise "Bad console!" else: print "Console passes sanity check." ip.End() """ def __init__(self, pathToBin, wkDir, *parms): self.proc = Process() self.proc.StartInfo.FileName = pathToBin self.proc.StartInfo.WorkingDirectory = wkDir self.proc.StartInfo.Arguments = " ".join(parms) self.proc.StartInfo.UseShellExecute = False self.proc.StartInfo.RedirectStandardOutput = True self.proc.StartInfo.RedirectStandardInput = True self.proc.StartInfo.RedirectStandardError = True def Start(self): if (not self.proc.Start()): return False else: self.reader = self.proc.StandardOutput self.reader2 = self.proc.StandardError self.writer = self.proc.StandardInput self.InitializeErrorWatcher() self.EatToPrompt() return True def StartAndRunToCompletion(self): if (not self.proc.Start()): return (False, None, None) else: self.reader = self.proc.StandardOutput self.reader2 = self.proc.StandardError self.writer = self.proc.StandardInput # This will hang if the output exceeds the buffer size output = self.reader.ReadToEnd() output2 = self.reader2.ReadToEnd() return (True, output, output2, self.proc.ExitCode) def EnsureInteractive(self): twoPlusTwoResult = self.ExecuteLine("2 + 2", True) if "4" <> twoPlusTwoResult: raise AssertionError, 'EnsureInteractive failed. 2+2 returned ' + twoPlusTwoResult # Note that the prompt text could occur in the middle of other output. # However, it is important to read all the output from the child process # to avoid deadlocks. Hence, we assume that ">>> " will only occur # as the prompt. def EatToPrompt(self, readError=False): result = self.EatToMarker(">>> ", readError) return result[0:-len(">>> ")] def EatToMarker(self, marker, readError=False): slurped = "" while not marker in slurped: nextChar = self.reader.Read() if nextChar == -1: raise ValueError("unexpected end of input after reading '%s'" % slurped) slurped += chr(nextChar) if slurped == '...': raise ValueError("found ... instead of %s, after reading %s" % (marker, slurped)) assert (slurped.endswith(marker)) if readError: # This should be returned as separate return values, instead of being appended together return self.ReadError() + slurped else: return slurped # Execute a single-line command, and return the output def ExecuteLine(self, line, readError=False): self.writer.Write(line + "\n") return self.EatToPrompt(readError)[0:-2] def ExecuteAndExit(self, line): self.writer.Write(line + "\n") i = 0 while i < 40 and not self.proc.HasExited: Thread.CurrentThread.Join(100) i += 1 return self.proc.ExitCode # Submit one line of a multi-line command to the console. There can be # multiple calls to ExecutePartialLine before a final call to ExecuteLine def ExecutePartialLine(self, line): self.writer.Write(line + "\n") ch = self.reader.Read() if ch == -1 or chr(ch) <> '.': raise AssertionError, 'missing the first dot' ch = self.reader.Read() if ch == -1 or chr(ch) <> '.': raise AssertionError, 'missing the second dot' ch = self.reader.Read() if ch == -1 or chr(ch) <> '.': raise AssertionError, 'missing the third dot' ch = self.reader.Read() if ch == -1 or chr(ch) <> ' ': raise AssertionError, 'missing the last space char' def End(self): if 'writer' in dir(self) and 'Close' in dir(self.writer): self.writer.Close() # Functions for the remote console def EnsureInteractiveRemote(self, readError=True): """Sometimes remote output can become available after the prompt is printed locally.""" twoPlusTwoResult = self.ExecuteLine("2 + 2", readError) if "4" == twoPlusTwoResult: return if "" <> twoPlusTwoResult: raise AssertionError, 'EnsureInteractive failed. 2+2 returned ' + twoPlusTwoResult twoPlusTwoResult = self.EatToMarker("4\r\n") if "4\r\n" <> twoPlusTwoResult: raise AssertionError, 'EnsureInteractive failed. 2+2 returned ' + twoPlusTwoResult def ExecuteLineRemote(self, line, expectedOutputLines=1): """Sometimes remote output can become available after the prompt is printed locally.""" result = self.ExecuteLine(line) if "" <> result: return result for i in xrange(expectedOutputLines): output = self.EatToMarker("\r\n") if output == "": raise AssertionError, 'ExecuteLineRemote failed. Returned empty after %s. Error is %s' % ( result, self.ReadError()) result += output return result[0:-2] # Functions to read stderr def InitializeErrorWatcher(self): from System.Threading import Thread, ThreadStart import thread self.errorLock = thread.allocate_lock() self.errorString = "" th = Thread(ThreadStart(self.WatchErrorStream)) th.IsBackground = True th.Start() def WatchErrorStream(self): while True: nextChar = self.reader2.Read() if (nextChar == -1): break self.errorLock.acquire() self.errorString += chr(nextChar) self.errorLock.release() def GetUnreadError(self): self.errorLock.acquire() result = self.errorString self.errorString = "" self.errorLock.release() return result def ReadError(self): # For reading the error stream, there is no marker to know when to stop reading. # Instead, we keep reading from the error stream until there is no text written # to it for 1 second. from time import sleep result = self.GetUnreadError() prev = result while True: sleep(1) result += self.GetUnreadError() if (result == prev): break prev = result return result
option2 = '"' + "JSONPARAMFILE=" + "'" + params['JSONPARAMSFILE'] + "'" + '"' print(option1) print(option2) option = option1 + option2 print(option) fijistr = ft.createFijistring(IMAGEJDIR, SCRIPT, jsonfilepath) fijistr = fijistr.replace('\\', '\\\\') print fijistr # start Fiji script in headless mode app = Process() #app.StartInfo.FileName = IMAGEJ app.StartInfo.FileName = "java" app.StartInfo.Arguments = fijistr app.Start() # wait until the script is finished app.WaitForExit() excode = app.ExitCode print('Exit Code: ', excode) print('Fiji Analysis Run Finished.') # read metadata JSON - the name of the file must be specified correctly md_out = jt.readjson(jsonfilepath) print('ResultTable: ', md_out['RESULTTABLE']) # initialize ZenTable object SingleObj = ZenTable() # read the result table and convert into a ZenTable SingleObj = ct.ReadResultTable(md_out['RESULTTABLE'], 1, '\t', 'FijiTable',
def __call__(self, *args, **kwargs): """Make a call to the wrapped function. Parameters ---------- args : list Positional arguments to be passed to the wrapped function. Default is ``[]``. kwargs : dict Named arguments to be passed to the wrapped function. Default is ``{}``. Returns ------- result: object or None The data returned by the wrapped call. The type of the return value depends on the implementation of the wrapped function. If something went wrong the value is ``None``. In this case, check the ``error`` attribute for more information. """ # if self.argtypes: # args = [arg for arg in args] # if self.kwargtypes: # kwargs = {name: value for name, value in kwargs.items()} idict = { 'args': args, 'kwargs': kwargs, # 'argtypes': self.argtypes, # 'kwargtypes': self.kwargtypes, # 'restypes': self.restypes } if self.serializer == 'json': with open(self.ipath, 'w+') as fo: json.dump(idict, fo, cls=DataEncoder) else: with open(self.ipath, 'wb+') as fo: pickle.dump(idict, fo, protocol=2) with open(self.opath, 'w+') as fh: fh.write('') env = compas._os.prepare_environment() args = [ WRAPPER, self.basedir, self.funcname, self.ipath, self.opath, self.serializer ] try: Popen except NameError: process = Process() for name in env: if process.StartInfo.EnvironmentVariables.ContainsKey(name): process.StartInfo.EnvironmentVariables[name] = env[name] else: process.StartInfo.EnvironmentVariables.Add(name, env[name]) process.StartInfo.UseShellExecute = False process.StartInfo.RedirectStandardOutput = True process.StartInfo.RedirectStandardError = True process.StartInfo.FileName = self.python process.StartInfo.Arguments = '-u -c "{0}" {1} {2} {3} {4} {5}'.format( *args) process.Start() process.WaitForExit() while True: line = process.StandardOutput.ReadLine() if not line: break line = line.strip() if self.callback: self.callback(line, self.callback_args) if self.verbose: print(line) # stderr = p.StandardError.ReadToEnd() else: process_args = [self.python, '-u', '-c'] + args process = Popen(process_args, stderr=PIPE, stdout=PIPE, env=env) while process.poll() is None: line = process.stdout.readline().strip() if self.callback: self.callback(line, self.callback_args) if self.verbose: print(line) if self.serializer == 'json': with open(self.opath, 'r') as fo: odict = json.load(fo, cls=DataDecoder) else: with open(self.opath, 'rb') as fo: odict = pickle.load(fo) self.data = odict['data'] self.profile = odict['profile'] self.error = odict['error'] if self.delete_files: try: os.remove(self.ipath) except OSError: pass try: os.remove(self.opath) except OSError: pass if self.error: raise Exception(self.error) return self.data
option2 = '"' + "JSONPARAMFILE=" + "'" + params['JSONPARAMSFILE'] + "'" + '"' print(option1) print(option2) option = option1 + option2 print(option) fijistr = ft.createFijistring(IMAGEJDIR, SCRIPT, jsonfilepath) fijistr = fijistr.replace('\\', '\\\\') print fijistr # start Fiji script in headless mode app = Process() #app.StartInfo.FileName = IMAGEJ app.StartInfo.FileName = "java" app.StartInfo.Arguments = fijistr app.Start() # wait until the script is finished app.WaitForExit() excode = app.ExitCode """ # start Fiji and execute the macro app = Process(); app.StartInfo.FileName = IMAGEJ app.StartInfo.Arguments = option app.Start() # wait until the script is finished app.WaitForExit() excode = app.ExitCode print('Exit Code: ', excode) """
import math import clr import time clr.AddReference("MissionPlanner") import MissionPlanner clr.AddReference("MissionPlanner.Utilities") # includes the Utilities class clr.AddReference("MissionPlanner.Comms") clr.AddReference("System") import MissionPlanner.Comms import System from System.Diagnostics import Process for i in range(20): workdir = 'C:\Users\michael\Documents\Mission Planner\sitl\d' + str(i) if not os.path.exists(workdir): os.makedirs(workdir) proc = Process() proc.StartInfo.WorkingDirectory = workdir proc.StartInfo.FileName ='C:\Users\michael\Documents\Mission Planner\sitl\ArduCopter.exe' proc.StartInfo.Arguments = ' -M+ -s1 --uartA tcp:0 --defaults ..\default_params\copter.parm --instance ' + str(i) + ' --home -35.363261,'+ str(149.165330 + 0.000001 * i) +',584,353' proc.Start() port = MissionPlanner.Comms.TcpSerial(); port.client = System.Net.Sockets.TcpClient("127.0.0.1", 5760 + 10 * i); mav = MissionPlanner.MAVLinkInterface(); mav.BaseStream = port; mav.getHeartBeat() #MissionPlanner.MainV2.instance.doConnect(mav, "preset", "0"); MissionPlanner.MainV2.Comports.Add(mav);
'\\Languages\\IronPython\\External\\Maui') try: clr.AddReference('Maui.Core.dll') except: print "test_superconsole.py failed: cannot load Maui.Core assembly" sys.exit(int(is_snap)) from Maui.Core import App proc = Process() proc.StartInfo.FileName = sys.executable proc.StartInfo.WorkingDirectory = testpath.rowan_root + '\\Languages\\IronPython\\Tests' proc.StartInfo.Arguments = '-X:TabCompletion -X:AutoIndent -X:ColorfulConsole' proc.StartInfo.UseShellExecute = True proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal proc.StartInfo.CreateNoWindow = False started = proc.Start() try: superConsole = App(proc.Id) except Exception as e: print "test_superconsole.py failed: cannot initialize App object (probably running as service, or in minimized remote window)" print "On VSLGO-MAUI machines close all remote desktop sessions using EXIT command on desktop!" proc.Kill() sys.exit(1) superConsole.SendKeys('from pretest import *{ENTER}') #------------------------------------------------------------------------------ #--Tests def test_newlines():