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 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 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 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 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 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
def create_verif1_report(data): #filename = r'\\radonc.hmr\Departements\Dosimétristes\STEREO FOIE\Calculs NTCP\test.pdf' filename = r'\\Mosaiqclsql\mosaiq_app\escan\vérif1_' + data[ 'patient_name'] + '_' + data['patient_number'] + '_' + data[ 'plan_name'] + '_' + data['beamset_name'] + '.pdf' doc = Document() #Add styles style = doc.Styles["Heading1"] style.Font.Size = 20 style.Font.Bold = True style.Font.Name = "Verdana" style.ParagraphFormat.Alignment = ParagraphAlignment.Center style.ParagraphFormat.SpaceAfter = 20 style = doc.Styles.AddStyle("TableHeader", "Normal") style.Font.Name = "Arial" style.ParagraphFormat.SpaceAfter = 4 style.ParagraphFormat.SpaceBefore = 4 style = doc.Styles.AddStyle("TableText", "Normal") style.Font.Name = "Arial" style.Font.Size = 8 style.ParagraphFormat.SpaceAfter = 4 style.ParagraphFormat.SpaceBefore = 4 #Add a section and set landscape orientation sec = doc.AddSection() pagesetup = doc.DefaultPageSetup.Clone() pagesetup.Orientation = Orientation.Portrait sec.PageSetup = pagesetup #Add a title sec.AddParagraph("Vérification initiale de la dosimétrie", "Heading1") # Add an image? #image = sec.AddImage('//radonc.hmr/Physiciens/Admin/Logo CIUSSS/Logo Ciusss couleur.png') #image.Width = "10cm" #Add patient information presc_text_temp = data['presc_text'].replace(" à ", " au ").split(" au ")[0] paragraph = sec.AddParagraph("Nom du patient: " + data['patient_name'], "Normal") paragraph.AddText("\n\nNuméro du dossier: " + data['patient_number']) paragraph.AddText("\n\nPlan: " + data['plan_name']) paragraph.AddText("\n\nBeamset: " + data['beamset_name']) paragraph.AddText("\n\nPrescription: " + presc_text_temp) paragraph.AddText("\n\nPlanifié par: " + data['planned_by_name']) paragraph.AddText("\n\nVérifié par: " + data['verified_by_name']) #Creat a table to hold the statistics paragraph = sec.AddParagraph() table = Table() table.Style = "TableText" table.Borders.Width = 0.75 col = table.AddColumn(Unit.FromCentimeter(3.5)) col.Format.Alignment = ParagraphAlignment.Left col = table.AddColumn(Unit.FromCentimeter(3)) col.Format.Alignment = ParagraphAlignment.Left col = table.AddColumn(Unit.FromCentimeter(11)) col.Format.Alignment = ParagraphAlignment.Left #Add header row header_row = table.AddRow() header_row.Style = "TableHeader" header_row.Shading.Color = Colors.LightBlue header_row.Cells[0].AddParagraph('ITEM') header_row.Cells[1].AddParagraph('VERIFICATION') header_row.Cells[2].AddParagraph('DESCRIPTION') #Add a row for each verification row = table.AddRow() row.Cells[0].AddParagraph('Bon scan sélectionné') row.Cells[1].AddParagraph(data['check_bonscan']) if data['check_bonscan'] == 'Pas vérifié': row.Cells[1].Shading.Color = Colors.Red row.Cells[2].AddParagraph('-') row = table.AddRow() row.Cells[0].AddParagraph('Scan') row.Cells[1].AddParagraph(data['check_scanOK']) if data['check_scanOK'] == 'Pas vérifié': row.Cells[1].Shading.Color = Colors.Red row.Cells[2].AddParagraph('-') row = table.AddRow() row.Cells[0].AddParagraph('Contour External et overrides') row.Cells[1].AddParagraph(data['check_ext']) if data['check_ext'] == 'Pas vérifié': row.Cells[1].Shading.Color = Colors.Red row.Cells[2].AddParagraph(data['ext_text']) if data['ext_text'] == 'Script pas roulé': row.Cells[2].Shading.Color = Colors.Red row = table.AddRow() row.Cells[0].AddParagraph('Contours') row.Cells[1].AddParagraph(data['check_contours']) if data['check_contours'] == 'Pas vérifié': row.Cells[1].Shading.Color = Colors.Red row.Cells[2].AddParagraph('-') row = table.AddRow() row.Cells[0].AddParagraph("Position de l'isocentre") row.Cells[1].AddParagraph(data['check_isoOK']) if data['check_isoOK'] == 'Pas vérifié': row.Cells[1].Shading.Color = Colors.Red row.Cells[2].AddParagraph(data['iso_text']) if data['iso_text'] == 'Script pas roulé': row.Cells[2].Shading.Color = Colors.Red row = table.AddRow() row.Cells[0].AddParagraph('Champs') row.Cells[1].AddParagraph(data['check_beams_Rx']) if data['check_beams_Rx'] == 'Pas vérifié': row.Cells[1].Shading.Color = Colors.Red row.Cells[2].AddParagraph(data['beam_text']) if data['beam_text'] == 'Script pas roulé': row.Cells[2].Shading.Color = Colors.Red row = table.AddRow() row.Cells[0].AddParagraph('Prescription') row.Cells[1].AddParagraph(data['check_beams_Rx']) if data['check_beams_Rx'] == 'Pas vérifié': row.Cells[1].Shading.Color = Colors.Red row.Cells[2].AddParagraph(data['presc_text']) if data['presc_text'] == 'Script pas roulé': row.Cells[2].Shading.Color = Colors.Red row = table.AddRow() row.Cells[0].AddParagraph("Paramètres d'optimisation et objectifs") row.Cells[1].AddParagraph(data['check_optimisation']) if data['check_optimisation'] == 'Pas vérifié': row.Cells[1].Shading.Color = Colors.Red row.Cells[2].AddParagraph(data['opt_text']) if data['opt_text'] == 'Script pas roulé': row.Cells[2].Shading.Color = Colors.Red row = table.AddRow() row.Cells[0].AddParagraph('DVH') row.Cells[1].AddParagraph(data['check_distribution_dose']) if data['check_distribution_dose'] == 'Pas vérifié': row.Cells[1].Shading.Color = Colors.Red row.Cells[2].AddParagraph('-') row = table.AddRow() row.Cells[0].AddParagraph('Distribution de dose') row.Cells[1].AddParagraph(data['check_distribution_dose']) if data['check_distribution_dose'] == 'Pas vérifié': row.Cells[1].Shading.Color = Colors.Red row.Cells[2].AddParagraph('-') #TEST - Format cells (this one works!) #for i, row in enumerate(table.Rows): # if i % 2 == 0: # row.Shading.Color = Colors.LightBlue #This also works #for i in range(5): # for j in range (2): #if table.Rows[i].Cells[j] == 'Pas vérifié': #table.Rows[i].Cells[j].Shading.Color = Colors.Red #Add table to the document sec.Add(table) #Render the document, save it to file and display the file renderer = PdfDocumentRenderer(True, Pdf.PdfFontEmbedding.Always) renderer.Document = doc renderer.RenderDocument() renderer.PdfDocument.Save(filename) process = Process() process.StartInfo.FileName = filename process.Start() process.WaitForExit()
class DotnetProcess(base.Process): def __init__(self, command, arguments=None, env=None, stdout=None, stderr=None, redirect_output=True, working_dir=None): self._cmdline = _get_cmd(command, arguments) self._process = CSharpProcess() self._started = False start_info = self._process.StartInfo start_info.FileName = self._cmdline[0] start_info.Arguments = self._cmdline[1:] self._env = env start_info.CreateNoWindow = True if working_dir is not None: start_info.WorkingDirectory = working_dir self._stdout = os.path.abspath(stdout) if stdout else None self._stderr = os.path.abspath(stderr) if stderr else None self._redirect_output = (stdout or stderr or redirect_output) if self._redirect_output: start_info.UseShellExecute = False start_info.RedirectStandardInput = True start_info.RedirectStandardOutput = True start_info.RedirectStandardError = True self._process.OutputDataReceived += self._stdout_handler self._process.ErrorDataReceived += self._stderr_handler self._stdout_lock = threading.Lock() if self._stdout: if os.path.isfile(self._stdout): shell.remove(self._stdout) self._stdout_ostream = IO.FileStream(self._stdout, IO.FileMode.Append, IO.FileAccess.Write, IO.FileShare.Read) self._stdout_istream = IO.FileStream(self._stdout, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.ReadWrite) self._stdout_writer = IO.StreamWriter(self._stdout_ostream) self._stdout_reader = IO.StreamReader(self._stdout_istream) else: self._stdout_buffer = b'' self._stderr_lock = threading.Lock() if self._stderr: if os.path.isfile(self._stderr): shell.remove(self._stderr) self._stderr_ostream = IO.FileStream(self._stderr, IO.FileMode.Append, IO.FileAccess.Write, IO.FileShare.Read) self._stderr_istream = IO.FileStream(self._stderr, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.ReadWrite) self._stderr_writer = IO.StreamWriter(self._stderr_ostream) self._stderr_reader = IO.StreamReader(self._stderr_istream) else: self._stderr_buffer = b'' else: start_info.UseShellExecute = True start_info.RedirectStandardInput = False start_info.RedirectStandardOutput = False start_info.RedirectStandardError = False self._pid = None self._immutable = None @classmethod def immutable(cls, pid, command): p = cls(command[0], command[1:]) p._pid = pid p._immutable = True return p def _stdout_handler(self, sender, outline): data = outline.Data if data is None: return with self._stdout_lock: if self._stdout: self._stdout_writer.WriteLine(data) self._stdout_writer.Flush() else: self._stdout_buffer += data def _stderr_handler(self, sender, outline): data = outline.Data if data is None: return with self._stderr_lock: if self._stderr: self._stderr_writer.WriteLine(data) self._stderr_writer.Flush() else: self._stderr_buffer += data @property def command(self): return self._cmdline[0] @property def arguments(self): return self._cmdline[1:] def start(self): if self._immutable: raise NotImplemented # Setup environment variables process_env = self._process.StartInfo.EnvironmentVariables for key, value in self._create_env(self._env).items(): process_env[six.text_type(key)] = six.text_type(value) self._process.Start() if self._redirect_output: self._process.BeginOutputReadLine() self._process.BeginErrorReadLine() self._started = True def kill(self): if self._immutable: kill(self.pid) elif self._started: self._process.Kill() self.wait() def wait(self, timeout=None): if self._immutable: raise NotImplemented if self._started: if timeout is not None: return self._process.WaitForExit(timeout) else: while self.is_running: time.sleep(1) return True return False @property def is_running(self): if self._immutable: raise NotImplemented return not self._process.HasExited if self._started else False @property def pid(self): return (self._pid if self._immutable else (self._process.Id if self._started else 0)) @property def exit_code(self): if self._immutable: raise NotImplemented if self._started and self._process.HasExited: return self._process.ExitCode return None def write(self, string): if self._immutable: raise NotImplemented if self._redirect_output: self._process.StandardInput.WriteLine(string) def read(self): if self._immutable: raise NotImplemented if self._redirect_output: with self._stdout_lock: if self._stdout: return self._stdout_reader.ReadToEnd() else: result = self._stdout_buffer self._stdout_buffer = b'' return result return b'' def eread(self): if self._immutable: raise NotImplemented if self._redirect_output: with self._stderr_lock: if self._stderr: return self._stderr_reader.ReadToEnd() else: result = self._stderr_buffer self._stderr_buffer = b'' return result return b''
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', SingleObj) # change the name of the table
def create_sample_report(): filename = r'\\radonc.hmr\Departements\Dosimétristes\STEREO FOIE\Calculs NTCP\test.pdf' doc = Document() #Add styles style = doc.Styles["Normal"] style.Font.Name = "Verdana" style.ParagraphFormat.SpaceAfter = 4 #style.ParagraphFormat.Shading.Color = Colors.SkyBlue style = doc.Styles["Heading1"] style.Font.Size = 20 style.Font.Bold = True style.Font.Name = "Verdana" #style.Font.Color = Colors.DeepSkyBlue style.ParagraphFormat.Alignment = ParagraphAlignment.Center style.ParagraphFormat.SpaceAfter = 10 # Create a new style called TextBox based on style Normal style = doc.Styles.AddStyle("TextBox", "Normal") style.ParagraphFormat.Alignment = ParagraphAlignment.Justify style.ParagraphFormat.Borders.Width = 2.5 style.ParagraphFormat.Borders.Distance = "3pt" style.ParagraphFormat.Shading.Color = Colors.Orange #Add a section and set landscape orientation sec = doc.AddSection() pagesetup = doc.DefaultPageSetup.Clone() pagesetup.Orientation = Orientation.Portrait sec.PageSetup = pagesetup #Add a title sec.AddParagraph("Première vérification", "Heading1") #Add patient information patient_name = "Bob Smith" patient_num = "1979" paragraph = sec.AddParagraph("Nom du patient: " + patient_name, "Normal") paragraph.AddText("\nNuméro HMR: " + patient_num) # Add an image? image = sec.AddImage(r'\\radonc.hmr\Dosimétristes\halloween2016.jpg') image.Width = "10cm" #Creat a table to hold the statistics table = Table() table.Borders.Width = 1 for i in range(5): col = table.AddColumn(Unit.FromCentimeter(3)) if i == 0: col.Format.Alignment = ParagraphAlignment.Left else: col.Format.Alignment = ParagraphAlignment.Right #Add header row header_row = table.AddRow() header_row.Shading.Color = Colors.SkyBlue header_row.Cells[0].AddParagraph('ROI') header_row.Cells[1].AddParagraph('Volume [cc]') header_row.Cells[2].AddParagraph('D99 [cGy]') header_row.Cells[3].AddParagraph('Average [cGy]') header_row.Cells[4].AddParagraph('D1 [cGy]') row = table.AddRow() row.Cells[0].AddParagraph('How') row.Cells[1].AddParagraph('are') row.Cells[2].AddParagraph('you') row.Cells[3].AddParagraph('doing') row.Cells[4].AddParagraph('today?') #Add table to the document sec.Add(table) #Render the document, save it to file and display the file renderer = PdfDocumentRenderer(True, Pdf.PdfFontEmbedding.Always) renderer.Document = doc renderer.RenderDocument() renderer.PdfDocument.Save(filename) process = Process() process.StartInfo.FileName = filename process.Start() process.WaitForExit()
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
def _xecute(funcname, basedir, tmpdir, delete_files, mode, *args, **kwargs): """Execute in a subprocess a function with optional positional and named arguments. Parameters: funcname (str): The full name of the function. basedir (str): A directory that should be added to the PYTHONPATH such that the function can be found. tmpdir (str): A directory that should be used for storing the IO files. delete_files (bool): Set to ``False`` if the IO files should not be deleted afterwards. mode (int): The printing mode. args (list): Optional. Positional arguments to be passed to the function. Default is ``[]``. kwargs (dict): Optional. Named arguments to be passed to the function. Default is ``{}``. """ if not basedir: basedir = '.' if not tmpdir: tmpdir = '.' if not os.path.isdir(basedir): raise Exception('basedir is not a directory: %s' % basedir) if not os.path.isdir(tmpdir): raise Exception('tmpdir is not a directory: %s' % tmpdir) if not os.access(tmpdir, os.W_OK): raise Exception('you do not have write access to tmpdir') ipath = os.path.join(tmpdir, '%s.in' % funcname) opath = os.path.join(tmpdir, '%s.out' % funcname) idict = {'args': args, 'kwargs': kwargs} with open(ipath, 'wb+') as fh: json.dump(idict, fh) with open(opath, 'wb+') as fh: fh.write('') p = Process() p.StartInfo.UseShellExecute = False p.StartInfo.RedirectStandardOutput = True p.StartInfo.RedirectStandardError = True p.StartInfo.FileName = 'pythonw' p.StartInfo.Arguments = '-u -c "{0}" {1} {2} {3} {4}'.format( WRAPPER, basedir, funcname, ipath, opath) p.Start() p.WaitForExit() while True: line = p.StandardOutput.ReadLine() if not line: break line = line.strip() if mode: print(line) stderr = p.StandardError.ReadToEnd() # print p.StandardOutput.ReadToEnd() # print p.ExitCode if stderr: odict = { 'error': stderr, 'data': None, 'iterations': None, 'profile': None } else: with open(opath, 'rb') as fh: odict = json.load(fh) if delete_files: try: os.remove(ipath) except OSError: pass try: os.remove(opath) except OSError: pass return odict