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
Пример #2
0
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
Пример #3
0
    def start_server(self):
        """Start the remote server.

        Returns
        -------
        ServerProxy
            Instance of the proxy, if the connection was successful.

        Raises
        ------
        RPCServerError
            If the server providing the requested service cannot be reached after
            100 contact attempts (*pings*).

        """
        env = compas._os.prepare_environment()

        try:
            Popen
        except NameError:
            self._process = Process()

            for name in env:
                if self._process.StartInfo.EnvironmentVariables.ContainsKey(name):
                    self._process.StartInfo.EnvironmentVariables[name] = env[name]
                else:
                    self._process.StartInfo.EnvironmentVariables.Add(name, env[name])

            self._process.StartInfo.UseShellExecute = False
            self._process.StartInfo.RedirectStandardOutput = True
            self._process.StartInfo.RedirectStandardError = True
            self._process.StartInfo.FileName = self.python
            self._process.StartInfo.Arguments = '-m {0} {1}'.format(self.service, str(self._port))
            self._process.Start()
        else:
            args = [self.python, '-m', self.service, str(self._port)]
            self._process = Popen(args, stdout=PIPE, stderr=STDOUT, env=env)

        server = ServerProxy(self.address)

        print("Starting a new proxy server...")

        success = False
        count = 100
        while count:
            try:
                server.ping()
            except:
                time.sleep(0.1)
                count -= 1
                print("    {} attempts left.".format(count))
            else:
                success = True
                break
        if not success:
            raise RPCServerError("The server is not available.")
        else:
            print("New proxy server started.")

        return server
Пример #4
0
    def SubmitHandler(self, sender, e):
        #Check if computer is part of a domain.
        try:
            clr.AddReference("System.DirectoryServices.ActiveDirectory")
            ctxType = ContextType.Domain
        except IOError:
            ctxType = ContextType.Machine

        ctx = PrincipalContext(ctxType)
        if ctx.ValidateCredentials(Env.UserName, self.inpBox.Text):
            startWatch.Stop()
            print "[+] CRED SUCCESS: Credentials validated against {0} -- {1}:{2}".format(
                ctx.ConnectedServer, Env.UserName, self.inpBox.Text)
            self.form.Dispose()
            self.form.Close()

            self.NewProcess = Process()
            self.NewProcess.StartInfo.FileName = self.path
            self.NewProcess.StartInfo.Arguments = self.proc['TargetInstance'][
                'CommandLine'].replace("\"{0}\"".format(self.path), "")
            GOT_CRED = True
        else:
            print "[-] CRED FAIL: Credentials failed against {0} -- {1}:{2}".format(
                Env.MachineName, Env.UserName, self.inpBox.Text)
            MessageBox.Show("Invalid Credentials!", "", MessageBoxButtons.OK,
                            MessageBoxIcon.Warning,
                            MessageBoxDefaultButton.Button1,
                            MessageBoxOptions.DefaultDesktopOnly)
Пример #5
0
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")
Пример #6
0
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()
Пример #7
0
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 __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
Пример #9
0
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
Пример #10
0
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()
Пример #11
0
    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
Пример #12
0
    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
Пример #13
0
    def start_server(self):
        """Start the remote server.

        Returns
        -------
        ServerProxy
            Instance of the proxy, if the connection was successful.

        Raises
        ------
        ThreadedServerError
            If the server providing the requested service cannot be reached.

        """
        if self.ping_server():
            print("Server running at {}...".format(self.address))
            return

        if compas.IPY:
            self._process = Process()
            for name in self._env:
                if self._process.StartInfo.EnvironmentVariables.ContainsKey(
                        name):
                    self._process.StartInfo.EnvironmentVariables[
                        name] = self._env[name]
                else:
                    self._process.StartInfo.EnvironmentVariables.Add(
                        name, self._env[name])
            self._process.StartInfo.UseShellExecute = False
            self._process.StartInfo.RedirectStandardOutput = True
            self._process.StartInfo.RedirectStandardError = True
            self._process.StartInfo.FileName = self._python
            self._process.StartInfo.Arguments = '-m {0} {1}'.format(
                'compas.remote.services.{}'.format(self._service),
                str(self._port))
            self._process.Start()

        else:
            args = [
                self._python, '-m',
                'compas.remote.services.{}'.format(self._service)
            ]
            self._process = Popen(args,
                                  stdout=PIPE,
                                  stderr=STDOUT,
                                  env=self._env)

        if not self.ping_server():
            raise ThreadedServerError("Server unavailable at {}...".format(
                self.address))

        print("Started {} service at {}...".format(self._service,
                                                   self.address))
Пример #14
0
	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)
Пример #15
0
 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)
Пример #16
0
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")
Пример #17
0
    def start_server(self):
        """Start the remote server.

        Returns
        -------
        ServerProxy
            Instance of the proxy, if the connection was successful.

        Raises
        ------
        ThreadedServerError
            If the server providing the requested service cannot be reached.

        """
        if self.ping_server():
            print("Server running at {}...".format(self.address))
            return

        if compas.IPY:
            self._process = Process()
            for name in self._env:
                if self._process.StartInfo.EnvironmentVariables.ContainsKey(name):
                    self._process.StartInfo.EnvironmentVariables[name] = self._env[name]
                else:
                    self._process.StartInfo.EnvironmentVariables.Add(name, self._env[name])
            self._process.StartInfo.UseShellExecute = False
            self._process.StartInfo.RedirectStandardOutput = True
            self._process.StartInfo.RedirectStandardError = True
            self._process.StartInfo.FileName = self._python
            self._process.StartInfo.Arguments = '-m {0} {1}'.format('compas.remote.services.{}'.format(self._service), str(self._port))
            self._process.Start()

        else:
            args = [self._python, '-m', 'compas.remote.services.{}'.format(self._service)]
            self._process = Popen(args, stdout=PIPE, stderr=STDOUT, env=self._env)

        # this doesn't work because (at least on my computer)
        # you have to allow the server to accept incoming connections
        # while you click on the dialog to confirm
        # the ping times out
        # and the function throws an error
        # it does start the server anyway though :)

        # if not self.ping_server():
        #     raise ThreadedServerError("Server unavailable at {}...".format(self.address))

        print("Started {} service at {}...".format(self._service, self.address))
Пример #18
0
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
Пример #19
0
    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
Пример #20
0
    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
Пример #21
0
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()
Пример #22
0
# 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()
Пример #23
0
    def start_server(self):
        """Start the remote server.

        Returns
        -------
        ServerProxy
            Instance of the proxy, if the connection was successful.

        Raises
        ------
        RPCServerError
            If the server providing the requested service cannot be reached after
            100 contact attempts (*pings*).

        Examples
        --------
        >>> p = Proxy()
        >>> p.stop_server()
        >>> p.start_server()

        """
        env = compas._os.prepare_environment()
        # this part starts the server side of the RPC setup
        # it basically launches a subprocess
        # to start the default service
        # the default service creates a server
        # and registers a dispatcher for custom functionality
        try:
            Popen
        except NameError:
            self._process = Process()

            for name in env:
                if self._process.StartInfo.EnvironmentVariables.ContainsKey(
                        name):
                    self._process.StartInfo.EnvironmentVariables[name] = env[
                        name]
                else:
                    self._process.StartInfo.EnvironmentVariables.Add(
                        name, env[name])
            self._process.StartInfo.UseShellExecute = False
            self._process.StartInfo.RedirectStandardOutput = True
            self._process.StartInfo.RedirectStandardError = True
            self._process.StartInfo.FileName = self.python
            self._process.StartInfo.Arguments = '-m {0} {1}'.format(
                self.service, str(self._port))
            self._process.Start()
        else:
            args = [self.python, '-m', self.service, str(self._port)]
            self._process = Popen(args, stdout=PIPE, stderr=PIPE, env=env)
        # this starts the client side
        # it creates a proxy for the server
        # and tries to connect the proxy to the actual server
        server = ServerProxy(self.address)
        print("Starting a new proxy server...")
        success = False
        count = 100
        while count:
            try:
                server.ping()
            except Exception:
                time.sleep(0.1)
                count -= 1
                print("    {} attempts left.".format(count))
            else:
                success = True
                break
        if not success:
            raise RPCServerError("The server is not available.")
        else:
            print("New proxy server started.")
        return server
Пример #24
0
# load and execute experiment
exp.Load('Count_Cells_Start_Fiji_from_Macro_Pos.czexp')
image = Zen.Acquisition.Execute(exp)
Zen.Application.Documents.Add(image)

# define Fiji analysis script
filename = image.FileName  # get the name of the current image data set
exeloc = 'C:\Users\Public\Documents\Fiji\ImageJ-win64.exe'
macro = '-macro Zen_Test\Count_Cells_EXP2_wellplate.ijm'  # specify the Fiji macro one wants to use
option = macro + ' ' + filename  # 'glue' together the options

# define status of Fiji
Fiji_Finished = False

# start Fiji and execute the macro
app = Process()
app.StartInfo.FileName = exeloc
app.StartInfo.Arguments = option
app.Start()

# check if Fiji already saved the data tables
while (Fiji_Finished == False):
    Fiji_Finished = File.Exists(filename[:-4] + '_Summary_Fiji.txt')

# read the data tables and convert them into Zen tables
rowoffset = 1  # skip ... lines
filename_R = filename[:-4] + '_Results_Fiji.txt'
filename_S = filename[:-4] + '_Summary_Fiji.txt'

# initialize ZenTable object
table_R = ZenTable()
Пример #25
0
# get the input values and store them
cziname = result.GetValue('czi')
macroname = result.GetValue('ijmacro')
runmacro = result.GetValue('RunMacro')
bfimport = result.GetValue('windowless')

CZI2Open = CZIdict[cziname]
Macro2Open = Macrodict[macroname]
print 'Send CZI     : ', CZI2Open

# use the absolute path --> this works always
exeloc = 'C:\Users\Public\Documents\Fiji\ImageJ-win64.exe'
if runmacro == True:
    print 'Run selected Fiji Macro : ', Macro2Open
    option =  '-macro ' + Macro2Open + ' ' + CZI2Open # 'glue' together the options
elif runmacro == False:
    print 'No special macro selected.'
    if bfimport == True:
        option = '-macro ' + bf_windowless + ' ' + CZI2Open
    if bfimport == False:
        option = CZI2Open

print 'Fiji Parameter : ', option

# start Fiji and execute the macro
app = Process();
app.StartInfo.FileName = exeloc
app.StartInfo.Arguments = option
app.Start()
Пример #26
0
    def start_server(self):
        """Start the remote server.

        Returns
        -------
        ServerProxy
            Instance of the proxy, if the connection was successful.

        Raises
        ------
        RPCServerError
            If the server providing the requested service cannot be reached after
            100 contact attempts (*pings*). The number of attempts is set by
            :attr:`Proxy.max_conn_attempts`.

        Examples
        --------
        >>> p = Proxy()  # doctest: +SKIP
        >>> p.stop_server()  # doctest: +SKIP
        >>> p.start_server()  # doctest: +SKIP

        """
        env = compas._os.prepare_environment()
        # this part starts the server side of the RPC setup
        # it basically launches a subprocess
        # to start the default service
        # the default service creates a server
        # and registers a dispatcher for custom functionality
        try:
            Popen
        except NameError:
            self._process = Process()
            for name in env:
                if self._process.StartInfo.EnvironmentVariables.ContainsKey(
                        name):
                    self._process.StartInfo.EnvironmentVariables[name] = env[
                        name]
                else:
                    self._process.StartInfo.EnvironmentVariables.Add(
                        name, env[name])
            self._process.StartInfo.UseShellExecute = False
            self._process.StartInfo.RedirectStandardOutput = self.capture_output
            self._process.StartInfo.RedirectStandardError = self.capture_output
            self._process.StartInfo.FileName = self.python
            self._process.StartInfo.Arguments = '-m {0} --port {1} --{2}autoreload'.format(
                self.service, self._port, '' if self.autoreload else 'no-')
            self._process.Start()
        else:
            args = [
                self.python, '-m', self.service, '--port',
                str(self._port),
                '--{}autoreload'.format('' if self.autoreload else 'no-')
            ]
            kwargs = dict(env=env)
            if self.capture_output:
                kwargs['stdout'] = PIPE
                kwargs['stderr'] = PIPE

            self._process = Popen(args, **kwargs)
        # this starts the client side
        # it creates a proxy for the server
        # and tries to connect the proxy to the actual server
        server = ServerProxy(self.address)
        print("Starting a new proxy server...")
        success = False
        attempt_count = 0
        while attempt_count < self.max_conn_attempts:
            try:
                server.ping()
            except Exception:
                time.sleep(0.1)
                attempt_count += 1
                print("    {} attempts left.".format(self.max_conn_attempts -
                                                     attempt_count))
            else:
                success = True
                break
        if not success:
            raise RPCServerError("The server is not available.")
        else:
            print("New proxy server started.")
        return server
Пример #27
0
    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
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);
Пример #29
0
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
Пример #30
0
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()