Python subprocess.STARTUPINFO() Examples

The following are code examples for showing how to use subprocess.STARTUPINFO(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Radium   Author: mehulj94   File: Radiumkeylogger.py    Apache License 2.0 6 votes vote down vote up
def subprocess_args(include_stdout=True):
    if hasattr(subprocess, 'STARTUPINFO'):
        si = subprocess.STARTUPINFO()
        si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        env = os.environ
    else:
        si = None
        env = None

    if include_stdout:
        ret = {'stdout:': subprocess.PIPE}
    else:
        ret = {}

    ret.update({'stdin': subprocess.PIPE,
                'stderr': subprocess.PIPE,
                'startupinfo': si,
                'env': env })
    return ret

#Function to get the Process ID 
Example 2
Project: sublime-solium-gutter   Author: sey   File: solium-gutter.py    MIT License 6 votes vote down vote up
def get_output(cmd):
    if int(sublime.version()) < 3000:
      if sublime.platform() != "windows":
        # Handle Linux and OS X in Python 2.
        run = '"' + '" "'.join(cmd) + '"'
        return commands.getoutput(run)
      else:
        # Handle Windows in Python 2.
        # Prevent console window from showing.
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        return subprocess.Popen(cmd, \
          stdout=subprocess.PIPE, \
          startupinfo=startupinfo).communicate()[0]
    else:
      # Handle all OS in Python 3.
      run = '"' + '" "'.join(cmd) + '"'
      try:
        return subprocess.check_output(run, stderr=subprocess.STDOUT, shell=True, env=os.environ)
      except Exception as exception:
        print(exception.output) 
Example 3
Project: imageio-ffmpeg   Author: imageio   File: _utils.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _is_valid_exe(exe):
    cmd = [exe, "-version"]
    try:
        with open(os.devnull, "w") as null:
            hide_window = None
            if os.name == 'nt':
                # stops executable from flashing on Windows
                hide_window = subprocess.STARTUPINFO()
                hide_window.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            subprocess.check_call(
                cmd, stdout=null, stderr=subprocess.STDOUT,
                startupinfo=hide_window
                )
        return True
    except (OSError, ValueError, subprocess.CalledProcessError):
        return False 
Example 4
Project: imageio-ffmpeg   Author: imageio   File: _utils.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def get_ffmpeg_version():
    """
    Get the version of the used ffmpeg executable (as a string).
    """
    exe = get_ffmpeg_exe()
    hide_window = None
    if os.name == 'nt':
        # stops executable from flashing on Windows
        hide_window = subprocess.STARTUPINFO()
        hide_window.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    line = subprocess.check_output(
        [exe, "-version"], startupinfo=hide_window
        ).split(b"\n", 1)[0]
    line = line.decode(errors="ignore").strip()
    version = line.split("version", 1)[-1].lstrip().split(" ", 1)[0].strip()
    return version 
Example 5
Project: script.mtvguide   Author: Mariusz89B   File: recordService.py    GNU General Public License v2.0 6 votes vote down vote up
def record(self, recordCommand, threadData):
        deb('RecordService record command: %s' % str(recordCommand))
        threadData['recordStartTime'] = datetime.datetime.now()
        output = ''
        si = None
        if os.name == 'nt':
            si = subprocess.STARTUPINFO()
            si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        recordEnviron = os.environ.copy()
        oldLdPath = recordEnviron.get("LD_LIBRARY_PATH", '')
        recordEnviron["LD_LIBRARY_PATH"] = os.path.join(os.path.dirname(recordCommand[0]), 'lib') + ':/lib:/usr/lib:/usr/local/lib'
        if oldLdPath != '':
            recordEnviron["LD_LIBRARY_PATH"] = recordEnviron["LD_LIBRARY_PATH"] + ":" + oldLdPath
        try:
            threadData['stopRecordTimer'] = threading.Timer(threadData['recordDuration'] + 5, self.stopRecord, [threadData])
            threadData['stopRecordTimer'].start()
            threadData['recordHandle'] = subprocess.Popen(recordCommand, shell=False, stdin=None, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, startupinfo=si, env=recordEnviron)
            output = threadData['recordHandle'].communicate()[0]
            returnCode = threadData['recordHandle'].returncode
            threadData['stopRecordTimer'].cancel()
            threadData['recordHandle'] = None
            deb('RecordService record finished, \noutput: %s, \nstatus: %d, Command: %s' % (output, returnCode, str(recordCommand)))
        except Exception, ex:
            deb('RecordService record exception: %s' % getExceptionString()) 
Example 6
Project: spied-on-u   Author: Lin8x   File: systeminfo.py    GNU General Public License v3.0 6 votes vote down vote up
def getWindows():
  
  def writeCommand(command):
    startupinfo = subprocess.STARTUPINFO()
    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    const = ((200 - len(command)) // 2)
    linestr = "-" * const + command + "-" * const
    output = subprocess.Popen(command, startupinfo=startupinfo, stdout=subprocess.PIPE)
    logger.write(str(output.stdout.read()).replace("\\r\\n", "\r\n"))
    logger.write("\n" + linestr + "\n")

  logger = open("systeminfowin.log", 'a+')
  writeCommand("Systeminfo")
  writeCommand("ipconfig")

#######################################################
#######################################################
####################################################### 
Example 7
Project: watools   Author: wateraccounting   File: raster_conversions.py    Apache License 2.0 6 votes vote down vote up
def Run_command_window(argument):
    """
    This function runs the argument in the command window without showing cmd window

    Keyword Arguments:
    argument -- string, name of the adf file
    """
    if os.name == 'posix':
        argument = argument.replace(".exe","")
        os.system(argument)

    else:
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

        process = subprocess.Popen(argument, startupinfo=startupinfo, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
        process.wait()

    return() 
Example 8
Project: sublime-win-bak   Author: okoala   File: HTMLPrettify.py    MIT License 6 votes vote down vote up
def get_output(cmd):
    if int(sublime.version()) < 3000:
      if sublime.platform() != "windows":
        # Handle Linux and OS X in Python 2.
        run = '"' + '" "'.join(cmd) + '"'
        return commands.getoutput(run)
      else:
        # Handle Windows in Python 2.
        # Prevent console window from showing.
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        return subprocess.Popen(cmd, \
          stdout=subprocess.PIPE, \
          startupinfo=startupinfo).communicate()[0]
    else:
      # Handle all OS in Python 3.
      run = '"' + '" "'.join(cmd) + '"'
      return subprocess.check_output(run, stderr=subprocess.STDOUT, shell=True, env=os.environ) 
Example 9
Project: sublime-win-bak   Author: okoala   File: node_bridge.py    MIT License 6 votes vote down vote up
def node_bridge(data, bin, args=[]):
	env = None
	startupinfo = None
	if IS_OSX:
		# GUI apps in OS X doesn't contain .bashrc/.zshrc set paths
		env = os.environ.copy()
		env['PATH'] += ':/usr/local/bin'
	if IS_WINDOWS:
		startupinfo = subprocess.STARTUPINFO()
		startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
	try:
		p = subprocess.Popen(['node', bin] + args,
			stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE,
			env=env, startupinfo=startupinfo)
	except OSError:
		raise Exception('Couldn\'t find Node.js. Make sure it\'s in your $PATH by running `node -v` in your command-line.')
	stdout, stderr = p.communicate(input=data.encode('utf-8'))
	stdout = stdout.decode('utf-8')
	stderr = stderr.decode('utf-8')
	if stderr:
		raise Exception('Error: %s' % stderr)
	else:
		return stdout 
Example 10
Project: sublime-win-bak   Author: okoala   File: HTMLPrettify.py    MIT License 6 votes vote down vote up
def get_output(cmd):
    if int(sublime.version()) < 3000:
      if sublime.platform() != "windows":
        # Handle Linux and OS X in Python 2.
        run = '"' + '" "'.join(cmd) + '"'
        return commands.getoutput(run)
      else:
        # Handle Windows in Python 2.
        # Prevent console window from showing.
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        return subprocess.Popen(cmd, \
          stdout=subprocess.PIPE, \
          startupinfo=startupinfo).communicate()[0]
    else:
      # Handle all OS in Python 3.
      run = '"' + '" "'.join(cmd) + '"'
      return subprocess.check_output(run, stderr=subprocess.STDOUT, shell=True, env=os.environ) 
Example 11
Project: sublime-standard-format   Author: bcomnes   File: standard-format.py    MIT License 6 votes vote down vote up
def command_version(command):
    """
    Uses subprocess to format a given string.
    """

    startupinfo = None

    if platform == "windows":
        # Prevent cmd.exe window from popping up
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= (
            subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
        )
        startupinfo.wShowWindow = subprocess.SW_HIDE

    std = subprocess.Popen(
        [command, "--version"],
        env=calculate_env(),
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        startupinfo=startupinfo
    )
    out, err = std.communicate()
    return out.decode("utf-8").replace("\r", ""), err 
Example 12
Project: DXMate   Author: jtowers   File: dxmate.py    MIT License 6 votes vote down vote up
def run_command(self):
        args = ['sfdx', 'force:apex:test:run', '-r', 'human',
                '-l', 'RunSpecifiedTests', '-n', self.class_name]
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             startupinfo=startupinfo, cwd=self.dx_folder)

        p.wait()

        out, err = p.communicate()
        r = p.returncode
        if p.returncode == 0:
            printer.write('\n' + str(out, 'utf-8'))
        else:
            printErr = err
            if err is None or err == '':
                printErr = out
            printer.write('\n' + str(printErr, 'utf-8')) 
Example 13
Project: DXMate   Author: jtowers   File: dxmate.py    MIT License 6 votes vote down vote up
def run_command(self):
        args = ['sfdx', 'force:apex:test:run', '-r', 'human']
        if not self.test_org is None and len(self.test_org) > 0:
            args.push('-u')
            args.push(self.input)
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             startupinfo=startupinfo, cwd=self.dx_folder)

        p.wait()

        out, err = p.communicate()
        r = p.returncode
        if p.returncode == 0:
            printer.write('\n' + str(out, 'utf-8'))
        else:
            printErr = err
            if err is None or err == '':
                printErr = out
            printer.write('\n' + str(printErr, 'utf-8')) 
Example 14
Project: DXMate   Author: jtowers   File: dxmate.py    MIT License 6 votes vote down vote up
def run_command(self):
        args = ['sfdx', 'force:source:push']
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             startupinfo=startupinfo, cwd=self.dx_folder)

        p.wait()

        out, err = p.communicate()
        r = p.returncode
        if p.returncode == 0:
            printer.write('\n' + str(out, 'utf-8'))
        else:
            printErr = err
            if not err is None and not err == '':
                printErr = out
            else:
                printer.write('\nError pushing source')
            printer.write('\n' + str(printErr, 'utf-8')) 
Example 15
Project: DXMate   Author: jtowers   File: dxmate.py    MIT License 6 votes vote down vote up
def run_command(self):
        args = ['sfdx', 'force:source:pull']
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             startupinfo=startupinfo, cwd=self.dx_folder)

        p.wait()

        out, err = p.communicate()
        r = p.returncode
        if p.returncode == 0:
            printer.write('\n' + str(out, 'utf-8'))
        else:
            printErr = err
            if not err is None and not err == '':
                printErr = out
            else:
                printer.write('\nError pulling source')
            printer.write('\n' + str(printErr, 'utf-8')) 
Example 16
Project: DXMate   Author: jtowers   File: dxmate.py    MIT License 6 votes vote down vote up
def run_command(self):
        args = ['sfdx', 'force:org:open']
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             startupinfo=startupinfo, cwd=self.dx_folder)

        p.wait()

        out, err = p.communicate()
        r = p.returncode
        if p.returncode == 0:
            printer.write('\nScratch org opened')
        else:
            printer.write('\nError opening')
            printer.write('\n' + str(err, 'utf-8')) 
Example 17
Project: DXMate   Author: jtowers   File: dxmate.py    MIT License 6 votes vote down vote up
def run_command(self):
        dx_folder = util.dxProjectFolder()
        args = ['sfdx', 'force:auth:web:login', '-d', '-s', '-a', 'DevHub']
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        p = subprocess.Popen(args, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)

        p.wait()

        out, err = p.communicate()
        r = p.returncode
        if p.returncode == 0:
            printer.write('\nDevHub authorized')
        else:
            printer.write('\nError authorizing Dev Hub:')
            printer.write('\n' + str(err, 'utf-8')) 
Example 18
Project: DXMate   Author: jtowers   File: dxmate.py    MIT License 6 votes vote down vote up
def run_command(self):
        dx_folder = util.dxProjectFolder()
        args = ['sfdx', 'force:visualforce:component:create',
                '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir]
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        p = subprocess.Popen(args, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)

        p.wait()

        out, err = p.communicate()
        r = p.returncode
        if p.returncode == 0:
            printer.write('\nVisaulforce Component created')
            file = os.path.join(self.class_dir, self.page_name + '.component')
            sublime.active_window().open_file(file)
        else:
            printer.write('\nError creating Visualforce Component:')
            printer.write('\n' + str(err, 'utf-8')) 
Example 19
Project: DXMate   Author: jtowers   File: dxmate.py    MIT License 6 votes vote down vote up
def run_command(self):
        dx_folder = util.dxProjectFolder()
        args = ['sfdx', 'force:visualforce:page:create',
                '-n', self.page_name,'-l', self.page_label, '-d', self.class_dir]
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        p = subprocess.Popen(args, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)

        p.wait()

        out, err = p.communicate()
        r = p.returncode
        if p.returncode == 0:
            printer.write('\nVisaulforce page created')
            file = os.path.join(self.class_dir, self.page_name + '.page')
            sublime.active_window().open_file(file)
        else:
            printer.write('\nError creating Visualforce page:')
            printer.write('\n' + str(err, 'utf-8')) 
Example 20
Project: DXMate   Author: jtowers   File: dxmate.py    MIT License 6 votes vote down vote up
def run_command(self):
        dx_folder = util.dxProjectFolder()
        args = ['sfdx', 'force:lightning:component:create',
                '-n', self.cmp_name, '-d', self.class_dir]
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        p = subprocess.Popen(args, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)

        p.wait()

        out, err = p.communicate()
        r = p.returncode
        if p.returncode == 0:
            printer.write('\nLightning Component created')
            file = os.path.join(self.class_dir, self.cmp_name, self.cmp_name + '.cmp')
            sublime.active_window().open_file(file)
        else:
            printer.write('\nError creating Lightning Component:')
            printer.write('\n' + str(err, 'utf-8')) 
Example 21
Project: DXMate   Author: jtowers   File: dxmate.py    MIT License 6 votes vote down vote up
def run_command(self):
        dx_folder = util.dxProjectFolder()
        args = ['sfdx', 'force:lightning:test:create',
                '-n', self.event_name, '-d', self.class_dir]
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        p = subprocess.Popen(args, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)

        p.wait()

        out, err = p.communicate()
        r = p.returncode
        if p.returncode == 0:
            printer.write('\nLightning Test created')
            file = os.path.join(self.class_dir, self.event_name + '.resource')
            sublime.active_window().open_file(file)
        else:
            printer.write('\nError creating Lightning Test:')
            printer.write('\n' + str(err, 'utf-8')) 
Example 22
Project: DXMate   Author: jtowers   File: dxmate.py    MIT License 6 votes vote down vote up
def run_command(self):
        dx_folder = util.dxProjectFolder()
        args = ['sfdx', 'force:lightning:interface:create',
                '-n', self.event_name, '-d', self.class_dir]
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        p = subprocess.Popen(args, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)

        p.wait()

        out, err = p.communicate()
        r = p.returncode
        if p.returncode == 0:
            printer.write('\nLightning Interface created')
            file = os.path.join(self.class_dir, self.event_name, self.event_name + '.intf')
            sublime.active_window().open_file(file)
        else:
            printer.write('\nError creating Lightning Interface:')
            printer.write('\n' + str(err, 'utf-8')) 
Example 23
Project: DXMate   Author: jtowers   File: dxmate.py    MIT License 6 votes vote down vote up
def run_command(self):
        dx_folder = util.dxProjectFolder()
        args = ['sfdx', 'force:lightning:event:create',
                '-n', self.event_name, '-d', self.class_dir]
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        p = subprocess.Popen(args, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)

        p.wait()

        out, err = p.communicate()
        r = p.returncode
        if p.returncode == 0:
            printer.write('\nLightning Event created')
            file = os.path.join(self.class_dir, self.event_name, self.event_name + '.evt')
            sublime.active_window().open_file(file)
        else:
            printer.write('\nError creating Lightning Event:')
            printer.write('\n' + str(err, 'utf-8')) 
Example 24
Project: DXMate   Author: jtowers   File: dxmate.py    MIT License 6 votes vote down vote up
def run_command(self):
        dx_folder = util.dxProjectFolder()
        args = ['sfdx', 'force:lightning:app:create',
                '-n', self.app_name, '-d', self.class_dir]
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        p = subprocess.Popen(args, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)

        p.wait()

        out, err = p.communicate()
        r = p.returncode
        if p.returncode == 0:
            printer.write('\nLightning App created')
            file = os.path.join(self.class_dir, self.app_name, self.app_name + '.app')
            sublime.active_window().open_file(file)
        else:
            printer.write('\nError creating Lightning App:')
            printer.write('\n' + str(err, 'utf-8')) 
Example 25
Project: DXMate   Author: jtowers   File: dxmate.py    MIT License 6 votes vote down vote up
def run_command(self):
        dx_folder = util.dxProjectFolder()
        args = ['sfdx', 'force:apex:class:create',
                '-n', self.class_name, '-d', self.class_dir]
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        p = subprocess.Popen(args, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)

        p.wait()

        out, err = p.communicate()
        r = p.returncode
        if p.returncode == 0:
            printer.write('\nApex class created')
            file = os.path.join(self.class_dir, self.class_name + '.cls')
            sublime.active_window().open_file(file)
        else:
            printer.write('\nError creating Apex Class:')
            printer.write('\n' + str(err, 'utf-8')) 
Example 26
Project: DXMate   Author: jtowers   File: dxmate.py    MIT License 6 votes vote down vote up
def run_command(self):
        args = ['sfdx', 'force:project:create', '-n', self.project_name,
                '-t', self.template, '-d', self.project_path]
        if self.namespace is not None and self.namespace != '':
            args.push('-s')
            args.push(self.namespace)
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        p = subprocess.Popen(args, stdout=subprocess.PIPE,
                             stderr=subprocess.STDOUT, startupinfo=startupinfo)

        p.wait()

        out,err = p.communicate()
        r = p.returncode
        if p.returncode == 0:
            printer.write('\nProject created')
        else:
            printer.write('\nError creating project:')
            printer.write('\n' + str(out, 'UTF-8')) 
Example 27
Project: DXMate   Author: jtowers   File: dxmate.py    MIT License 6 votes vote down vote up
def run_command(self):
        args = ['sfdx', 'force:apex:execute', '-f', self.file_path]
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             startupinfo=startupinfo, cwd=self.dx_folder)

        p.wait()

        out, err = p.communicate()
        r = p.returncode
        if p.returncode == 0:
            printer.write('\nFinished running apex')
            printer.write('\n' + str(out, 'utf-8'))
        else:
            printErr = err
            if err is None or err == '':
                printErr = out
            printer.write('\nError running apex')
            printer.write('\n' + str(printErr, 'utf-8')) 
Example 28
Project: VSCMT   Author: drew-wallace   File: util.py    MIT License 6 votes vote down vote up
def execute_command(command, working_dir=None):
    startupinfo = None
    # hide console window on windows
    if os.name == 'nt':
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

    output = None
    try:
        output = subprocess.check_output(
            command,
            cwd=working_dir,
            startupinfo=startupinfo
        )
    except (subprocess.CalledProcessError, AttributeError):
        # Git will return an error when the given directory
        # is not a repository, which means that we can ignore this error
        pass
    else:
        output = str(output, encoding="utf-8").strip()

    return output 
Example 29
Project: pyblish-win   Author: pyblish   File: test_subprocess.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_startupinfo(self):
        # startupinfo argument
        # We uses hardcoded constants, because we do not want to
        # depend on win32all.
        STARTF_USESHOWWINDOW = 1
        SW_MAXIMIZE = 3
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags = STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = SW_MAXIMIZE
        # Since Python is a console process, it won't be affected
        # by wShowWindow, but the argument should be silently
        # ignored
        subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
                        startupinfo=startupinfo) 
Example 30
Project: smoke-zephyr   Author: zeroSteiner   File: utilities.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def open_uri(uri):
	"""
	Open a URI in a platform intelligent way. On Windows this will use
	'cmd.exe /c start' and on Linux this will use gvfs-open or xdg-open
	depending on which is available. If no suitable application can be
	found to open the URI, a RuntimeError will be raised.

	.. versionadded:: 1.3.0

	:param str uri: The URI to open.
	"""
	close_fds = True
	startupinfo = None
	proc_args = []
	if sys.platform.startswith('win'):
		proc_args.append(which('cmd.exe'))
		proc_args.append('/c')
		proc_args.append('start')
		uri = uri.replace('&', '^&')
		close_fds = False
		startupinfo = subprocess.STARTUPINFO()
		startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
		startupinfo.wShowWindow = subprocess.SW_HIDE
	elif which('gvfs-open'):
		proc_args.append(which('gvfs-open'))
	elif which('xdg-open'):
		proc_args.append(which('xdg-open'))
	else:
		raise RuntimeError('could not find suitable application to open uri')
	proc_args.append(uri)
	proc_h = subprocess.Popen(proc_args, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=close_fds, startupinfo=startupinfo)
	return proc_h.wait() == 0 
Example 31
Project: Repobot   Author: Desgard   File: popen_spawn.py    MIT License 5 votes vote down vote up
def __init__(self, cmd, timeout=30, maxread=2000, searchwindowsize=None,
                 logfile=None, cwd=None,  env=None, encoding=None,
                 codec_errors='strict'):
        super(PopenSpawn, self).__init__(timeout=timeout, maxread=maxread,
                searchwindowsize=searchwindowsize, logfile=logfile,
                encoding=encoding, codec_errors=codec_errors)

        kwargs = dict(bufsize=0, stdin=subprocess.PIPE,
                      stderr=subprocess.STDOUT, stdout=subprocess.PIPE,
                      cwd=cwd, env=env)

        if sys.platform == 'win32':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            kwargs['startupinfo'] = startupinfo
            kwargs['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP

        if not isinstance(cmd, (list, tuple)):
            cmd = shlex.split(cmd)

        self.proc = subprocess.Popen(cmd, **kwargs)
        self.closed = False
        self._buf = self.string_type()

        self._read_queue = Queue()
        self._read_thread = threading.Thread(target=self._read_incoming)
        self._read_thread.setDaemon(True)
        self._read_thread.start() 
Example 32
Project: flight-lab   Author: google   File: windows.py    Apache License 2.0 5 votes vote down vote up
def _launch_app(self):
    args = [self._bin_path] + self._arguments
    self.logger.debug('[App - {0}] Executing "{1}"...'.format(
        self._name, ' '.join(args)))

    self.emit('starting', self)

    proc = None
    info = subprocess.STARTUPINFO()
    if self._start_minimized:
      info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
      info.wShowWindow = _SW_MINIMIZE

    try:
      proc = subprocess.Popen(
          args,
          cwd=self._working_dir,
          creationflags=subprocess.CREATE_NEW_CONSOLE,
          close_fds=True,
          startupinfo=info)
    except Exception as e:
      self.logger.debug('[App - {0}] Failed to launch. {1}'.format(
          self._name, e))
      return None

    self.emit('started', self)
    return proc 
Example 33
Project: ncm2   Author: ncm2   File: ncm2.py    MIT License 5 votes vote down vote up
def __init__(self, *args, **keys):
            if 'startupinfo' not in keys:
                si = subprocess.STARTUPINFO()
                si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                keys['startupinfo'] = si
            cls.__init__(self, *args, **keys) 
Example 34
Project: Pancas   Author: Sup3Roque   File: nhlcom.py    GNU General Public License v2.0 5 votes vote down vote up
def run(self, url, selectGame ,side):

        if selectGame == None or side == None:
            return control.resolve(int(sys.argv[1]), True, control.item(path=url))

        command = ['java','-jar',jarFile,selectGame,side]

        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

        self.process = subprocess.Popen(command,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            startupinfo=startupinfo)

        if os.name == 'posix':
            success = False
            success, output = FuckNeulionClient.request_proxy_hack(selectGame,side)

        control.sleep(1000)

        control.resolve(int(sys.argv[1]), True, control.item(path=url))

        for i in range(0, 240):
            if self.isPlayingVideo(): break
            control.sleep(1000)
        while self.isPlayingVideo():
            control.sleep(1000)
        control.sleep(5000) 
Example 35
Project: Pancas   Author: Sup3Roque   File: nhlcom.py    GNU General Public License v2.0 5 votes vote down vote up
def run(self, url, selectGame ,side):

        if selectGame == None or side == None:
            return control.resolve(int(sys.argv[1]), True, control.item(path=url))

        command = ['java','-jar',jarFile,selectGame,side]

        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

        self.process = subprocess.Popen(command,
            stdout=subprocess.PIPE,
            stderr=subprocess.STDOUT,
            startupinfo=startupinfo)

        if os.name == 'posix':
            success = False
            success, output = FuckNeulionClient.request_proxy_hack(selectGame,side)

        control.sleep(1000)

        control.resolve(int(sys.argv[1]), True, control.item(path=url))

        for i in range(0, 240):
            if self.isPlayingVideo(): break
            control.sleep(1000)
        while self.isPlayingVideo():
            control.sleep(1000)
        control.sleep(5000) 
Example 36
Project: honeybee   Author: ladybug-tools   File: pyrad_proc.py    GNU General Public License v3.0 5 votes vote down vote up
def __configure_subprocess(self):
        '''Prevent subprocess module failure in frozen scripts on Windows.
           Prevent console windows from popping up when not console based.
           Make sure we use the version-specific string types.
        '''
        # On Windows, sys.stdxxx may not be available when:
        # - built as *.exe with "pyinstaller --noconsole"
        # - invoked via CreateProcess() and stream not redirected
        try:
            sys.__stdin__.fileno()
            self._stdin = sys.stdin
        except BaseException:
            self._stdin = PIPE
        try:
            sys.__stdout__.fileno()
            self._stdout = sys.stdout
        except BaseException:
            self._stdout = PIPE
        try:
            sys.__stderr__.fileno()
            self._stderr = sys.stderr
        # keep subprocesses from opening their own console.
        except BaseException:
            self._stderr = PIPE
        if hasattr(subprocess, 'STARTUPINFO'):
            si = subprocess.STARTUPINFO()
            si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            self._pipeargs = {'startupinfo': si}
        else:
            self._pipeargs = {}
        # type names vary between Py2.7 and 3.x
        self._strtypes = (type(b''), type(u'')) 
Example 37
Project: Dolphin-Updater   Author: nbear3   File: data_control.py    GNU General Public License v3.0 5 votes vote down vote up
def _call_proc(*proc_args):
    starti = subprocess.STARTUPINFO()
    starti.dwFlags |= subprocess.STARTF_USESHOWWINDOW
    subprocess.call(proc_args, startupinfo=starti,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.STDOUT,
                    stdin=subprocess.PIPE) 
Example 38
Project: NiujiaoDebugger   Author: MrSrc   File: test_subprocess.py    GNU General Public License v3.0 5 votes vote down vote up
def test_startupinfo(self):
        # startupinfo argument
        # We uses hardcoded constants, because we do not want to
        # depend on win32all.
        STARTF_USESHOWWINDOW = 1
        SW_MAXIMIZE = 3
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags = STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = SW_MAXIMIZE
        # Since Python is a console process, it won't be affected
        # by wShowWindow, but the argument should be silently
        # ignored
        subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
                        startupinfo=startupinfo) 
Example 39
Project: NiujiaoDebugger   Author: MrSrc   File: test_subprocess.py    GNU General Public License v3.0 5 votes vote down vote up
def test_startupinfo_keywords(self):
        # startupinfo argument
        # We use hardcoded constants, because we do not want to
        # depend on win32all.
        STARTF_USERSHOWWINDOW = 1
        SW_MAXIMIZE = 3
        startupinfo = subprocess.STARTUPINFO(
            dwFlags=STARTF_USERSHOWWINDOW,
            wShowWindow=SW_MAXIMIZE
        )
        # Since Python is a console process, it won't be affected
        # by wShowWindow, but the argument should be silently
        # ignored
        subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
                        startupinfo=startupinfo) 
Example 40
Project: NiujiaoDebugger   Author: MrSrc   File: test_subprocess.py    GNU General Public License v3.0 5 votes vote down vote up
def test_startupinfo_copy(self):
        # bpo-34044: Popen must not modify input STARTUPINFO structure
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = subprocess.SW_HIDE

        # Call Popen() twice with the same startupinfo object to make sure
        # that it's not modified
        for _ in range(2):
            cmd = [sys.executable, "-c", "pass"]
            with open(os.devnull, 'w') as null:
                proc = subprocess.Popen(cmd,
                                        stdout=null,
                                        stderr=subprocess.STDOUT,
                                        startupinfo=startupinfo)
                with proc:
                    proc.communicate()
                self.assertEqual(proc.returncode, 0)

            self.assertEqual(startupinfo.dwFlags,
                             subprocess.STARTF_USESHOWWINDOW)
            self.assertIsNone(startupinfo.hStdInput)
            self.assertIsNone(startupinfo.hStdOutput)
            self.assertIsNone(startupinfo.hStdError)
            self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
            self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []}) 
Example 41
Project: NiujiaoDebugger   Author: MrSrc   File: test_subprocess.py    GNU General Public License v3.0 5 votes vote down vote up
def test_empty_attribute_list(self):
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.lpAttributeList = {}
        subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
                        startupinfo=startupinfo) 
Example 42
Project: package_coverage   Author: codexns   File: package_coverage.py    MIT License 5 votes vote down vote up
def git_commit_info(package_dir):
    """
    Get the git SHA1 hash, commit date and summary for the current git commit

    :param package_dir:
        A unicode string of the filesystem path to the folder containing the
        package

    :return:
        A tuple containing:
        [0] A unicode string of the short commit hash
        [1] A datetime.datetime object of the commit date
        [2] A unicode string of the commit message summary
    """

    startupinfo = None
    if sys.platform == 'win32':
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

    _, env = shellenv.get_env(for_subprocess=True)
    proc = subprocess.Popen(
        ['git', 'log', '-n', '1', "--pretty=format:%h %at %s", 'HEAD'],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        env=env,
        cwd=package_dir,
        startupinfo=startupinfo
    )
    stdout, stderr = proc.communicate()
    if stderr:
        raise OSError(stderr.decode('utf-8').strip())
    parts = stdout.decode('utf-8').strip().split(' ', 2)
    return (parts[0], datetime.utcfromtimestamp(int(parts[1])), parts[2]) 
Example 43
Project: package_coverage   Author: codexns   File: package_coverage.py    MIT License 5 votes vote down vote up
def is_git_clean(package_dir):
    """
    Detects if the git repository is currently all committed

    :param package_dir:
        A unicode string of the filesystem path to the folder containing the
        package

    :return:
        A boolean - if the repository is clean
    """

    startupinfo = None
    if sys.platform == 'win32':
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

    _, env = shellenv.get_env(for_subprocess=True)
    proc = subprocess.Popen(
        ['git', 'status', '--porcelain'],
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        env=env,
        cwd=package_dir,
        startupinfo=startupinfo
    )
    stdout, stderr = proc.communicate()
    if stderr:
        raise OSError(stderr.decode('utf-8').strip())
    return len(stdout.decode('utf-8').strip()) == 0 
Example 44
Project: noora   Author: janripke   File: StartupInfoFactory.py    GNU General Public License v3.0 5 votes vote down vote up
def new_startup_info():
        startup_info = None
        if os.name == 'nt':
            startup_info = subprocess.STARTUPINFO()
            # USESHOWWINDOW
            startup_info.dwFlags |= 1
            # SW_HIDE
            startup_info.wShowWindow = 0
        return startup_info 
Example 45
Project: noora   Author: janripke   File: StartupInfoFactory.py    GNU General Public License v3.0 5 votes vote down vote up
def newStartupInfo():
    startupInfo=None
    if os.name=='nt':    
      startupInfo=subprocess.STARTUPINFO()
      #USESHOWWINDOW
      startupInfo.dwFlags |=1
      #SW_HIDE
      startupInfo.wShowWindow=0
    return startupInfo 
Example 46
Project: noora   Author: janripke   File: OracleConnector.py    GNU General Public License v3.0 5 votes vote down vote up
def getStartupInfo(self):
    startupInfo=None
    if os.name=='nt':    
      startupInfo=subprocess.STARTUPINFO()
      #USESHOWWINDOW
      startupInfo.dwFlags |=1
      #SW_HIDE
      startupInfo.wShowWindow=0
    return startupInfo 
Example 47
Project: noora   Author: janripke   File: SqlLoaderConnector.py    GNU General Public License v3.0 5 votes vote down vote up
def getStartupInfo(self):
    startupInfo=None
    if os.name=='nt':    
      startupInfo=subprocess.STARTUPINFO()
      #USESHOWWINDOW
      startupInfo.dwFlags |=1
      #SW_HIDE
      startupInfo.wShowWindow=0
    return startupInfo 
Example 48
Project: noora   Author: janripke   File: LoadJavaConnector.py    GNU General Public License v3.0 5 votes vote down vote up
def getStartupInfo(self):
    startupInfo = None
    if os.name == 'nt':
      startupInfo = subprocess.STARTUPINFO()
      # USESHOWWINDOW
      startupInfo.dwFlags |= 1
      # SW_HIDE
      startupInfo.wShowWindow = 0
    return startupInfo 
Example 49
Project: ironpython2   Author: IronLanguages   File: test_subprocess.py    Apache License 2.0 5 votes vote down vote up
def test_startupinfo(self):
        # startupinfo argument
        # We uses hardcoded constants, because we do not want to
        # depend on win32all.
        STARTF_USESHOWWINDOW = 1
        SW_MAXIMIZE = 3
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags = STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = SW_MAXIMIZE
        # Since Python is a console process, it won't be affected
        # by wShowWindow, but the argument should be silently
        # ignored
        subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
                        startupinfo=startupinfo) 
Example 50
Project: D-VAE   Author: muhanzhang   File: windows.py    MIT License 5 votes vote down vote up
def subprocess_Popen(command, **params):
    """
    Utility function to work around windows behavior that open windows.

    :see: call_subprocess_Popen and output_subprocess_Popen
    """
    startupinfo = None
    if os.name == 'nt':
        startupinfo = subprocess.STARTUPINFO()
        try:
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        except AttributeError:
            startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW

        # Anaconda for Windows does not always provide .exe files
        # in the PATH, they also have .bat files that call the corresponding
        # executable. For instance, "g++.bat" is in the PATH, not "g++.exe"
        # Unless "shell=True", "g++.bat" is not executed when trying to
        # execute "g++" without extensions.
        # (Executing "g++.bat" explicitly would also work.)
        params['shell'] = True

    # Using the dummy file descriptors below is a workaround for a
    # crash experienced in an unusual Python 2.4.4 Windows environment
    # with the default None values.
    stdin = None
    if "stdin" not in params:
        stdin = open(os.devnull)
        params['stdin'] = stdin.fileno()

    try:
        proc = subprocess.Popen(command, startupinfo=startupinfo, **params)
    finally:
        if stdin is not None:
            del stdin
    return proc 
Example 51
Project: sublime-win-bak   Author: okoala   File: Babel.py    MIT License 5 votes vote down vote up
def node_bridge(data, bin, args=[]):
	env = None
	startupinfo = None
	if os_name == 'osx':
		# GUI apps in OS X doesn't contain .bashrc/.zshrc set paths
		env = os.environ.copy()
		env['PATH'] += ':/usr/local/bin'
	elif os_name == 'windows':
		startupinfo = subprocess.STARTUPINFO()
		startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
	try:
		p = subprocess.Popen(
			['node', bin] + args,
			stdout=subprocess.PIPE,
			stdin=subprocess.PIPE,
			stderr=subprocess.PIPE,
			env=env,
			startupinfo=startupinfo
		)
	except OSError:
		raise Exception('Error: Couldn\'t find "node" in "%s"' % env['PATH'])
	stdout, stderr = p.communicate(input=data.encode('utf-8'))
	stdout = stdout.decode('utf-8')
	stderr = stderr.decode('utf-8')
	if stderr:
		raise Exception('Error: %s' % stderr)
	else:
		return stdout 
Example 52
Project: LaZagne   Author: AlessandroZ   File: execute_cmd.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def save_hives():
    """
    Save SAM Hives
    """
    for h in constant.hives:
        if not os.path.exists(constant.hives[h]):
            try:
                cmdline = 'reg.exe save hklm\%s %s' % (h, constant.hives[h])
                command = ['cmd.exe', '/c', cmdline]
                info = subprocess.STARTUPINFO()
                info.dwFlags = STARTF_USESHOWWINDOW
                info.wShowWindow = SW_HIDE
                p = subprocess.Popen(command, startupinfo=info, stdin=subprocess.PIPE, stderr=subprocess.STDOUT,
                                     stdout=subprocess.PIPE, universal_newlines=True)
                results, _ = p.communicate()
            except Exception as e:
                print_debug('ERROR', u'Failed to save system hives: {error}'.format(error=e))
                return False
    return True 
Example 53
Project: Grok-backdoor   Author: deepzec   File: server.py    GNU General Public License v3.0 5 votes vote down vote up
def launchTunnelWithoutConsole(command, port):
    """Launches 'command' windowless and waits until finished"""
#    startupinfo = subprocess.STARTUPINFO()
#    startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
#    startupinfo.wShowWindow = subprocess.SW_HIDE
#    subprocess.Popen([command, 'tcp', port], startupinfo=startupinfo)
    if ostype == 'windows':
        os.popen2('START /B '+command+' tcp '+port)

    else:
        os.popen2(command+' tcp '+port + ' &') 
Example 54
Project: sublime-standard-format   Author: bcomnes   File: standard-format.py    MIT License 5 votes vote down vote up
def standard_format(string, command):
    """
    Uses subprocess to format a given string.
    """

    startupinfo = None

    if platform == "windows":
        # Prevent cmd.exe window from popping up
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags |= (
            subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
        )
        startupinfo.wShowWindow = subprocess.SW_HIDE

    std = subprocess.Popen(
        command,
        env=calculate_env(),
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
        startupinfo=startupinfo
    )

    std.stdin.write(bytes(string, 'UTF-8'))
    out, err = std.communicate()
    print(err)
    return out.decode("utf-8"), None 
Example 55
Project: sublime-format   Author: Rypac   File: command.py    MIT License 5 votes vote down vote up
def shell(command, paths=[]):
    startup_info = None
    if os.name == 'nt':
        startup_info = subprocess.STARTUPINFO()
        startup_info.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        startup_info.wShowWindow = subprocess.SW_HIDE

    env = os.environ.copy()
    if paths:
        env['PATH'] = os.pathsep.join(paths) + os.pathsep + env['PATH']

    def run(input, *args, **kwargs):
        process = subprocess.Popen(
            command,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            startupinfo=startup_info,
            env=env,
            shell=False,
            universal_newlines=True)
        stdout, stderr = process.communicate(input=input)
        ok = process.returncode == 0
        return ok, stdout, stderr

    return run 
Example 56
Project: Graphvizer   Author: hao-lee   File: graphvizer.py    GNU General Public License v2.0 5 votes vote down vote up
def dot_thread(self):
		while True:
			# Clear items before the last item
			while self.queue_rendering.qsize() > 1:
				self.queue_rendering.get()
			contents = self.queue_rendering.get(block=True, timeout=None)

			'''
			For purpose of cross-platform, we can't use TemporaryFile class because
			subprocess can't read it directly on Windows. Using a regular file is a
			good choice.
			'''
			with open(file=self.intermediate_file, mode="w", encoding="utf-8") as fd:
				fd.write(contents)

			cmd = [gvzsettings.dot_cmd_path, self.intermediate_file, "-Tpng", "-o", gvzsettings.image_filepath]
			# For Windows, we must use startupinfo to hide the console window.
			startupinfo = None
			if os.name == "nt":
				startupinfo = subprocess.STARTUPINFO()
				startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
			process = subprocess.Popen(cmd, stdout=subprocess.PIPE,
											stderr=subprocess.PIPE,
											startupinfo=startupinfo)
			# Terminate the dot process if it takes too long to complete.
			try:
				stdout, stderr = process.communicate(timeout=gvzsettings.dot_timeout)
			except subprocess.TimeoutExpired:
				process.kill()
				stdout, stderr = process.communicate()
			if len(stdout) != 0:
				self.print(stdout)
			if len(stderr) != 0:
				self.print(stderr) 
Example 57
Project: DXMate   Author: jtowers   File: dxmate.py    MIT License 5 votes vote down vote up
def run_command(self):
        dx_folder = util.dxProjectFolder()
        args = ['sfdx', 'force:data:soql:query',
                '-q', self.query]
        startupinfo = None
        if os.name == 'nt':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        p = subprocess.Popen(args, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE, startupinfo=startupinfo, cwd=dx_folder)

        p.wait()

        out, err = p.communicate()
        r = p.returncode
        if p.returncode == 0:
            printer.write('\nOpening results file')
            content = str(out,'UTF-8')
            #try:
            #    parsed = json.loads(content)
            #    content = json.dumps(parsed,  sort_keys=True,indent=1, separators=(',', ':'))
            #    util.debug(content)
            #except Exception as e:
            #    util.debug('could not format query results\n', e)
            file = sublime.active_window().new_file()
            file.set_scratch(True)
            file.set_name('SOQL')
            syntax_path = None
            if "linux" in sys.platform or "darwin" in sys.platform:
                syntax_path = os.path.join("Packages",plugin_name(),"sublime","lang","JSON.tmLanguage")
            else:
                syntax_path = os.path.join("Packages/"+plugin_name()+"/sublime/lang/JSON.tmLanguage")
            #file.set_syntax_file(syntax_path)
            file.run_command("insert", {"characters":content})
        else:
            printer.write('\nError running query:')
            printer.write('\n' + str(err, 'utf-8')) 
Example 58
Project: DXMate   Author: jtowers   File: languageServer.py    MIT License 5 votes vote down vote up
def start_server():
    deleteDbIfExists()
    working_dir = os.path.join(util.get_plugin_folder(), 'apex-jorje-lsp.jar')
    java_cmd = 'java'
    java_path = util.get_setting('java_path')
    util.debug(java_path)
    if java_path != '':
        java_cmd = os.path.join(java_path, java_cmd)

    util.debug('using java path: ', java_cmd)
    args = [java_cmd, '-cp', working_dir, '-Ddebug.internal.errors=true','-Ddebug.semantic.errors=false',
            'apex.jorje.lsp.ApexLanguageServerLauncher']
    util.debug("starting " + str(args))
    si = None
    if os.name == "nt":
        si = subprocess.STARTUPINFO()  # type: ignore
        si.dwFlags |= subprocess.SW_HIDE | subprocess.STARTF_USESHOWWINDOW  # type: ignore
    try:
        process = subprocess.Popen(
            args,
            stdin=subprocess.PIPE,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
            cwd=util.dxProjectFolder(),
            startupinfo=si)
        return Client(process)

    except Exception as err:
        util.debug(err) 
Example 59
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_subprocess.py    GNU General Public License v2.0 5 votes vote down vote up
def test_startupinfo(self):
        # startupinfo argument
        # We uses hardcoded constants, because we do not want to
        # depend on win32all.
        STARTF_USESHOWWINDOW = 1
        SW_MAXIMIZE = 3
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags = STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = SW_MAXIMIZE
        # Since Python is a console process, it won't be affected
        # by wShowWindow, but the argument should be silently
        # ignored
        subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
                        startupinfo=startupinfo) 
Example 60
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_subprocess.py    GNU General Public License v2.0 5 votes vote down vote up
def test_startupinfo_keywords(self):
        # startupinfo argument
        # We use hardcoded constants, because we do not want to
        # depend on win32all.
        STARTF_USERSHOWWINDOW = 1
        SW_MAXIMIZE = 3
        startupinfo = subprocess.STARTUPINFO(
            dwFlags=STARTF_USERSHOWWINDOW,
            wShowWindow=SW_MAXIMIZE
        )
        # Since Python is a console process, it won't be affected
        # by wShowWindow, but the argument should be silently
        # ignored
        subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
                        startupinfo=startupinfo) 
Example 61
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_subprocess.py    GNU General Public License v2.0 5 votes vote down vote up
def test_startupinfo_copy(self):
        # bpo-34044: Popen must not modify input STARTUPINFO structure
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags = subprocess.STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = subprocess.SW_HIDE

        # Call Popen() twice with the same startupinfo object to make sure
        # that it's not modified
        for _ in range(2):
            cmd = [sys.executable, "-c", "pass"]
            with open(os.devnull, 'w') as null:
                proc = subprocess.Popen(cmd,
                                        stdout=null,
                                        stderr=subprocess.STDOUT,
                                        startupinfo=startupinfo)
                with proc:
                    proc.communicate()
                self.assertEqual(proc.returncode, 0)

            self.assertEqual(startupinfo.dwFlags,
                             subprocess.STARTF_USESHOWWINDOW)
            self.assertIsNone(startupinfo.hStdInput)
            self.assertIsNone(startupinfo.hStdOutput)
            self.assertIsNone(startupinfo.hStdError)
            self.assertEqual(startupinfo.wShowWindow, subprocess.SW_HIDE)
            self.assertEqual(startupinfo.lpAttributeList, {"handle_list": []}) 
Example 62
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_subprocess.py    GNU General Public License v2.0 5 votes vote down vote up
def test_empty_attribute_list(self):
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.lpAttributeList = {}
        subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
                        startupinfo=startupinfo) 
Example 63
Project: pipeline   Author: liorbenhorin   File: email.py    MIT License 5 votes vote down vote up
def _invoke(self, cmdline):
        if sys.platform[:3] == 'win':
            closefds = False
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        else:
            closefds = True
            startupinfo = None

        if (os.environ.get('DISPLAY') or sys.platform[:3] == 'win' or
                                                    sys.platform == 'darwin'):
            inout = file(os.devnull, 'r+')
        else:
            # for TTY programs, we need stdin/out
            inout = None

        # if possible, put the child precess in separate process group,
        # so keyboard interrupts don't affect child precess as well as
        # Python
        setsid = getattr(os, 'setsid', None)
        if not setsid:
            setsid = getattr(os, 'setpgrp', None)

        pipe = subprocess.Popen(cmdline, stdin=inout, stdout=inout,
                                stderr=inout, close_fds=closefds,
                                preexec_fn=setsid, startupinfo=startupinfo)

        # It is assumed that this kind of tools (gnome-open, kfmclient,
        # exo-open, xdg-open and open for OSX) immediately exit after lauching
        # the specific application
        returncode = pipe.wait()
        if hasattr(self, 'fixreturncode'):
            returncode = self.fixreturncode(returncode)
        return not returncode 
Example 64
Project: oss-ftp   Author: aliyun   File: test_subprocess.py    MIT License 5 votes vote down vote up
def test_startupinfo(self):
        # startupinfo argument
        # We uses hardcoded constants, because we do not want to
        # depend on win32all.
        STARTF_USESHOWWINDOW = 1
        SW_MAXIMIZE = 3
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.dwFlags = STARTF_USESHOWWINDOW
        startupinfo.wShowWindow = SW_MAXIMIZE
        # Since Python is a console process, it won't be affected
        # by wShowWindow, but the argument should be silently
        # ignored
        subprocess.call([sys.executable, "-c", "import sys; sys.exit(0)"],
                        startupinfo=startupinfo) 
Example 65
Project: poker   Author: surgebiswas   File: windows.py    MIT License 5 votes vote down vote up
def subprocess_Popen(command, **params):
    """
    Utility function to work around windows behavior that open windows.

    :see: call_subprocess_Popen and output_subprocess_Popen
    """
    startupinfo = None
    if os.name == 'nt':
        startupinfo = subprocess.STARTUPINFO()
        try:
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
        except AttributeError:
            startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW

        # Anaconda for Windows does not always provide .exe files
        # in the PATH, they also have .bat files that call the corresponding
        # executable. For instance, "g++.bat" is in the PATH, not "g++.exe"
        # Unless "shell=True", "g++.bat" is not executed when trying to
        # execute "g++" without extensions.
        # (Executing "g++.bat" explicitly would also work.)
        params['shell'] = True

    # Using the dummy file descriptors below is a workaround for a
    # crash experienced in an unusual Python 2.4.4 Windows environment
    # with the default None values.
    stdin = None
    if "stdin" not in params:
        stdin = open(os.devnull)
        params['stdin'] = stdin.fileno()

    try:
        proc = subprocess.Popen(command, startupinfo=startupinfo, **params)
    finally:
        if stdin is not None:
            del stdin
    return proc 
Example 66
Project: BehaveToolkit   Author: mixxorz   File: behave_command.py    MIT License 5 votes vote down vote up
def _launch_process(self, command, print_stream=False):
        """Launches a process and returns its output as a string.

        If print_stream=True, it will also stream the output to an output
        panel.

        Raises an exception if behave is not configured properly.
        """

        startupinfo = None
        if sublime.platform() == 'windows':
            # Prevent Windows from opening a console when starting a process
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

        process = subprocess.Popen(command,
                                   stdout=subprocess.PIPE,
                                   bufsize=1,
                                   universal_newlines=True,
                                   cwd=self.view.window().folders()[0],
                                   startupinfo=startupinfo)

        if print_stream:
            self.erase()
            streamer = StreamerThread(self.append, process.stdout)
            streamer.start()
            streamer.join()

        stdout, stderr = process.communicate()

        if re.match(r'ConfigError', stdout):
            raise Exception("An error occurred while launching behave.\n",
                            stdout)

        return stdout 
Example 67
Project: sublime-text-conda   Author: mandeep   File: commands.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def startupinfo(self):
        """Property used to hide command prompts when on Windows platforms."""
        startupinfo = None

        if sys.platform == 'win32':
            startupinfo = subprocess.STARTUPINFO()

            if sys.version_info.major == 3:
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            else:
                startupinfo.dwFlags |= subprocess._subprocess.STARTF_USESHOWWINDOW

        return startupinfo 
Example 68
Project: sketch-wakatime   Author: wakatime   File: compat.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        startupinfo = kwargs.get('startupinfo')
        if is_win or True:
            try:
                startupinfo = startupinfo or subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            except AttributeError:
                pass
        kwargs['startupinfo'] = startupinfo
        if 'env' not in kwargs:
            kwargs['env'] = os.environ.copy()
            kwargs['env']['LANG'] = 'en-US' if is_win else 'en_US.UTF-8'
        subprocess.Popen.__init__(self, *args, **kwargs) 
Example 69
Project: pipenv   Author: pypa   File: popen_spawn.py    MIT License 5 votes vote down vote up
def __init__(self, cmd, timeout=30, maxread=2000, searchwindowsize=None,
                 logfile=None, cwd=None, env=None, encoding=None,
                 codec_errors='strict', preexec_fn=None):
        super(PopenSpawn, self).__init__(timeout=timeout, maxread=maxread,
                searchwindowsize=searchwindowsize, logfile=logfile,
                encoding=encoding, codec_errors=codec_errors)

        # Note that `SpawnBase` initializes `self.crlf` to `\r\n`
        # because the default behaviour for a PTY is to convert
        # incoming LF to `\r\n` (see the `onlcr` flag and
        # https://stackoverflow.com/a/35887657/5397009). Here we set
        # it to `os.linesep` because that is what the spawned
        # application outputs by default and `popen` doesn't translate
        # anything.
        if encoding is None:
            self.crlf = os.linesep.encode ("ascii")
        else:
            self.crlf = self.string_type (os.linesep)

        kwargs = dict(bufsize=0, stdin=subprocess.PIPE,
                      stderr=subprocess.STDOUT, stdout=subprocess.PIPE,
                      cwd=cwd, preexec_fn=preexec_fn, env=env)

        if sys.platform == 'win32':
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            kwargs['startupinfo'] = startupinfo
            kwargs['creationflags'] = subprocess.CREATE_NEW_PROCESS_GROUP

        if isinstance(cmd, string_types) and sys.platform != 'win32':
            cmd = shlex.split(cmd, posix=os.name == 'posix')

        self.proc = subprocess.Popen(cmd, **kwargs)
        self.pid = self.proc.pid
        self.closed = False
        self._buf = self.string_type()

        self._read_queue = Queue()
        self._read_thread = threading.Thread(target=self._read_incoming)
        self._read_thread.setDaemon(True)
        self._read_thread.start() 
Example 70
Project: eden   Author: facebookexperimental   File: __init__.py    GNU General Public License v2.0 5 votes vote down vote up
def _resolvesockname(self):
        # if invoked via a trigger, watchman will set this env var; we
        # should use it unless explicitly set otherwise
        path = os.getenv("WATCHMAN_SOCK")
        if path:
            return path

        cmd = [self.binpath, "--output-encoding=bser", "get-sockname"]
        try:
            args = dict(stdout=subprocess.PIPE, stderr=subprocess.PIPE)  # noqa: C408

            if os.name == "nt":
                # if invoked via an application with graphical user interface,
                # this call will cause a brief command window pop-up.
                # Using the flag STARTF_USESHOWWINDOW to avoid this behavior.
                startupinfo = subprocess.STARTUPINFO()
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
                args["startupinfo"] = startupinfo

            p = subprocess.Popen(cmd, **args)

        except OSError as e:
            raise WatchmanError('"watchman" executable not in PATH (%s)', e)

        stdout, stderr = p.communicate()
        exitcode = p.poll()

        if exitcode:
            raise WatchmanError("watchman exited with code %d" % exitcode)

        result = bser.loads(stdout)
        if "error" in result:
            raise WatchmanError("get-sockname error: %s" % result["error"])

        return result["sockname"] 
Example 71
Project: NiujiaoDebugger   Author: MrSrc   File: test_subprocess.py    GNU General Public License v3.0 4 votes vote down vote up
def test_close_fds_with_stdio(self):
        import msvcrt

        fds = os.pipe()
        self.addCleanup(os.close, fds[0])
        self.addCleanup(os.close, fds[1])

        handles = []
        for fd in fds:
            os.set_inheritable(fd, True)
            handles.append(msvcrt.get_osfhandle(fd))

        p = subprocess.Popen([sys.executable, "-c",
                              "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
                             stdout=subprocess.PIPE, close_fds=False)
        stdout, stderr = p.communicate()
        self.assertEqual(p.returncode, 0)
        int(stdout.strip())  # Check that stdout is an integer

        p = subprocess.Popen([sys.executable, "-c",
                              "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
        stdout, stderr = p.communicate()
        self.assertEqual(p.returncode, 1)
        self.assertIn(b"OSError", stderr)

        # The same as the previous call, but with an empty handle_list
        handle_list = []
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.lpAttributeList = {"handle_list": handle_list}
        p = subprocess.Popen([sys.executable, "-c",
                              "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             startupinfo=startupinfo, close_fds=True)
        stdout, stderr = p.communicate()
        self.assertEqual(p.returncode, 1)
        self.assertIn(b"OSError", stderr)

        # Check for a warning due to using handle_list and close_fds=False
        with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.lpAttributeList = {"handle_list": handles[:]}
            p = subprocess.Popen([sys.executable, "-c",
                                  "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                 startupinfo=startupinfo, close_fds=False)
            stdout, stderr = p.communicate()
            self.assertEqual(p.returncode, 0) 
Example 72
Project: pyblish-deadline   Author: pyblish   File: deadline.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def CallDeadlineCommand(self, arguments, hideWindow=True):
        # On OSX, we look for the DEADLINE_PATH file. On other platforms,
        # we use the environment variable.
        if os.path.exists("/Users/Shared/Thinkbox/DEADLINE_PATH"):
            with open("/Users/Shared/Thinkbox/DEADLINE_PATH") as f:
                deadlineBin = f.read().strip()
                deadlineCommand = deadlineBin + "/deadlinecommand"
        else:
            deadlineBin = os.environ["DEADLINE_PATH"]
            if os.name == "nt":
                deadlineCommand = deadlineBin + "\\deadlinecommand.exe"
            else:
                deadlineCommand = deadlineBin + "/deadlinecommand"

        startupinfo = None
        if hideWindow and os.name == "nt" and hasattr(subprocess,
                                                      "STARTF_USESHOWWINDOW"):
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

        environment = {}
        for key in os.environ.keys():
            environment[key] = str(os.environ[key])

        # Need to set the PATH, cuz windows seems to load DLLs from the PATH
        # earlier that cwd....
        if os.name == "nt":
            path = str(deadlineBin + os.pathsep + os.environ["PATH"])
            environment["PATH"] = path

        arguments.insert(0, deadlineCommand)

        # Specifying PIPE for all handles to
        # workaround a Python bug on Windows.
        # The unused handles are then closed immediatley afterwards.
        proc = subprocess.Popen(arguments, cwd=deadlineBin,
                                stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                startupinfo=startupinfo,
                                env=environment)
        proc.stdin.close()
        proc.stderr.close()

        output = proc.stdout.read()

        return output 
Example 73
Project: HEG_ESP32   Author: moothyknight   File: MplayerCtrl.py    MIT License 4 votes vote down vote up
def _start_process(self, media_file, mplayer_args):
        if not self.Parent.IsShown():
            raise BuildProcessError('parent windows must be shown, '
                                    'use .Show()')
        if not mplayer_args is None:
            args = [self.mplayer_path, '-wid', self.Handle,
                    '-msglevel', 'all=4']
            args.extend(mplayer_args)
        else:
            args = [self.mplayer_path, '-wid', self.Handle,
                    '-slave',
                    '-noconsolecontrols', '-nofontconfig', '-idle',
                    '-msglevel', 'all=4']
        # required args
        for tup in [('-vo', VO_DRIVER), ('-ao', AO_DRIVER), ('-slave', False),
                    ('-idle', False), ('-input', 'conf=' + devnull)]:
            if not tup[0] in args:
                args.extend(tup)
        args.extend(('-input', 'nodefault-bindings'))
        # -
        if not media_file is None:
            args.append(media_file)
        
        if not self.sound:
            args.append('-nosound')
        
        startupinfo = None
        if sys.platform == 'win32': # suppress console window
            startupinfo = STARTUPINFO()
            startupinfo.dwFlags |= STARTF_USESHOWWINDOW
            
        if self._process is None:
            args = [unicode(arg).encode(sys.getfilesystemencoding())
                    for arg in filter(None, args)]
            self.args = args
            try:
                _debug(args, 'args')
                self._process = Popen(args, bufsize=4096, stdin=PIPE, stdout=PIPE,
                                      stderr=PIPE, universal_newlines=True,
                                      startupinfo=startupinfo)
            except Exception, e:
                raise BuildProcessError(str(e))
            self._stdin = self._process.stdin
            self._stdout = self._process.stdout
            self._stderr = self._process.stderr
            self.msoe = MplayerStdoutEvents(self, self._stdout, self._stdout_queue)
            self.msee = MplayerStderrEvents(self, self._stderr, self.msoe)
            self.msoe.start()
            self.msee.start() 
Example 74
Project: sublime-text-3-packages   Author: nickjj   File: util.py    MIT License 4 votes vote down vote up
def popen(cmd, stdout=None, stderr=None, output_stream=STREAM_BOTH, env=None, extra_env=None):
    """Open a pipe to an external process and return a Popen object."""

    info = None

    if os.name == 'nt':
        info = subprocess.STARTUPINFO()
        info.dwFlags |= subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
        info.wShowWindow = subprocess.SW_HIDE

    if output_stream == STREAM_BOTH:
        stdout = stdout or subprocess.PIPE
        stderr = stderr or subprocess.PIPE
    elif output_stream == STREAM_STDOUT:
        stdout = stdout or subprocess.PIPE
        stderr = subprocess.DEVNULL
    else:  # STREAM_STDERR
        stdout = subprocess.DEVNULL
        stderr = stderr or subprocess.PIPE

    if env is None:
        env = create_environment()

    if extra_env is not None:
        env.update(extra_env)

    try:
        return subprocess.Popen(
            cmd,
            stdin=subprocess.PIPE,
            stdout=stdout,
            stderr=stderr,
            startupinfo=info,
            env=env
        )
    except Exception as err:
        from . import persist
        persist.printf('ERROR: could not launch', repr(cmd))
        persist.printf('reason:', str(err))
        persist.printf('PATH:', env.get('PATH', ''))


# view utils 
Example 75
Project: ros2cli   Author: ros2   File: daemon.py    Apache License 2.0 4 votes vote down vote up
def spawn_daemon(args, wait_until_spawned=None, debug=False):
    ros_domain_id = int(os.environ.get('ROS_DOMAIN_ID', 0))
    kwargs = {}
    if platform.system() != 'Windows':
        cmd = ['_ros2_daemon']
    else:
        # allow closing the shell the daemon was spawned from
        # while the daemon is still running
        cmd = [
            sys.executable,
            os.path.join(
                os.path.dirname(os.path.dirname(__file__)),
                'daemon/__init__.py')]
        # Process Creation Flag documented in the MSDN
        DETACHED_PROCESS = 0x00000008  # noqa: N806
        kwargs.update(creationflags=DETACHED_PROCESS)
        # avoid showing cmd windows for subprocess
        si = subprocess.STARTUPINFO()
        si.dwFlags = subprocess.STARTF_USESHOWWINDOW
        si.wShowWindow = subprocess.SW_HIDE
        kwargs['startupinfo'] = si
        # don't keep handle of current working directory in daemon process
        kwargs.update(cwd=os.environ.get('SYSTEMROOT', None))

    rmw_implementation_identifier = rclpy.get_rmw_implementation_identifier()
    if rmw_implementation_identifier is None:
        raise RuntimeError(
            'Unable to get rmw_implementation_identifier, '
            'try specifying the implementation to use via the '
            "'RMW_IMPLEMENTATION' environment variable")
    cmd.extend([
        # the arguments are only passed for visibility in e.g. the process list
        '--rmw-implementation', rmw_implementation_identifier,
        '--ros-domain-id', str(ros_domain_id)])
    if not debug:
        kwargs['stdout'] = subprocess.DEVNULL
        kwargs['stderr'] = subprocess.DEVNULL
    subprocess.Popen(cmd, **kwargs)

    if wait_until_spawned is None:
        return True

    if wait_until_spawned > 0.0:
        timeout = time.time() + wait_until_spawned
    else:
        timeout = None
    while True:
        if is_daemon_running(args):
            return True
        time.sleep(0.1)
        if timeout is not None and time.time() >= timeout:
            return None 
Example 76
Project: sublime-win-bak   Author: okoala   File: util.py    MIT License 4 votes vote down vote up
def popen(cmd, stdout=None, stderr=None, output_stream=STREAM_BOTH, env=None, extra_env=None):
    """Open a pipe to an external process and return a Popen object."""

    info = None

    if os.name == 'nt':
        info = subprocess.STARTUPINFO()
        info.dwFlags |= subprocess.STARTF_USESTDHANDLES | subprocess.STARTF_USESHOWWINDOW
        info.wShowWindow = subprocess.SW_HIDE

    if output_stream == STREAM_BOTH:
        stdout = stdout or subprocess.PIPE
        stderr = stderr or subprocess.PIPE
    elif output_stream == STREAM_STDOUT:
        stdout = stdout or subprocess.PIPE
        stderr = subprocess.DEVNULL
    else:  # STREAM_STDERR
        stdout = subprocess.DEVNULL
        stderr = stderr or subprocess.PIPE

    if env is None:
        env = create_environment()

    if extra_env is not None:
        env.update(extra_env)

    try:
        return subprocess.Popen(
            cmd,
            stdin=subprocess.PIPE,
            stdout=stdout,
            stderr=stderr,
            startupinfo=info,
            env=env
        )
    except Exception as err:
        from . import persist
        persist.printf('ERROR: could not launch', repr(cmd))
        persist.printf('reason:', str(err))
        persist.printf('PATH:', env.get('PATH', ''))


# view utils 
Example 77
Project: LaZagne   Author: AlessandroZ   File: execute_cmd.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def powershell_execute(script, func):
    """
    Execute a powershell script
    """
    output = ""
    try:
        script = re.sub("Write-Verbose ", "Write-Output ", script, flags=re.I)
        script = re.sub("Write-Error ", "Write-Output ", script, flags=re.I)
        script = re.sub("Write-Warning ", "Write-Output ", script, flags=re.I)

        full_args = ["powershell.exe", "-NoProfile", "-NoLogo", "-C", "-"]

        info = subprocess.STARTUPINFO()
        info.dwFlags = STARTF_USESHOWWINDOW
        info.wShowWindow = SW_HIDE

        p = subprocess.Popen(full_args, startupinfo=info, stdin=subprocess.PIPE, stderr=subprocess.STDOUT,
                             stdout=subprocess.PIPE, universal_newlines=True, shell=True)
        p.stdin.write("$base64=\"\"" + "\n")

        n = 25000
        b64_script = base64.b64encode(script)
        tab = [b64_script[i:i + n] for i in range(0, len(b64_script), n)]
        for t in tab:
            p.stdin.write("$base64+=\"%s\"\n" % t)
            p.stdin.flush()

        p.stdin.write("$d=[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($base64))\n")
        p.stdin.write("Invoke-Expression $d\n")

        p.stdin.write("\n$a=Invoke-Expression \"%s\" | Out-String\n" % func)
        p.stdin.write("$b=[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes(\"$a\"))\n")
        p.stdin.write("Write-Host \"[BEGIN]\"\n")
        p.stdin.write("Write-Host $b\n")

        # begin flag used to remove possible bullshit output print before the func is launched
        if '[BEGIN]' in p.stdout.readline():
            # Get the result in base64
            for i in p.stdout.readline():
                output += i
            output = base64.b64decode(output)
    except Exception:
        pass

    return output 
Example 78
Project: LaZagne   Author: AlessandroZ   File: ie.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def history_from_powershell(self):
        # From https://richardspowershellblog.wordpress.com/2011/06/29/ie-history-to-csv/
        cmdline = '''
        function get-iehistory {
        [CmdletBinding()]
        param ()
        
        $shell = New-Object -ComObject Shell.Application
        $hist = $shell.NameSpace(34)
        $folder = $hist.Self
        
        $hist.Items() | 
        foreach {
            if ($_.IsFolder) {
            $siteFolder = $_.GetFolder
            $siteFolder.Items() | 
            foreach {
                $site = $_
            
                if ($site.IsFolder) {
                $pageFolder  = $site.GetFolder
                $pageFolder.Items() | 
                foreach {
                    $visit = New-Object -TypeName PSObject -Property @{        
                        URL = $($pageFolder.GetDetailsOf($_,0))           
                    }
                    $visit
                }
                }
            }
            }
        }
        }
        get-iehistory
        '''
        command = ['powershell.exe', '/c', cmdline]
        info = subprocess.STARTUPINFO()
        info.dwFlags = STARTF_USESHOWWINDOW
        info.wShowWindow = SW_HIDE
        p = subprocess.Popen(command, startupinfo=info, stderr=subprocess.STDOUT, stdout=subprocess.PIPE,
                             stdin=subprocess.PIPE, universal_newlines=True)
        results, _ = p.communicate()

        urls = []
        for r in results.split('\n'):
            if r.startswith('http'):
                urls.append(r.strip())
        return urls 
Example 79
Project: cqp-sdk-for-py37-native   Author: crud-boy   File: test_subprocess.py    GNU General Public License v2.0 4 votes vote down vote up
def test_close_fds_with_stdio(self):
        import msvcrt

        fds = os.pipe()
        self.addCleanup(os.close, fds[0])
        self.addCleanup(os.close, fds[1])

        handles = []
        for fd in fds:
            os.set_inheritable(fd, True)
            handles.append(msvcrt.get_osfhandle(fd))

        p = subprocess.Popen([sys.executable, "-c",
                              "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
                             stdout=subprocess.PIPE, close_fds=False)
        stdout, stderr = p.communicate()
        self.assertEqual(p.returncode, 0)
        int(stdout.strip())  # Check that stdout is an integer

        p = subprocess.Popen([sys.executable, "-c",
                              "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
        stdout, stderr = p.communicate()
        self.assertEqual(p.returncode, 1)
        self.assertIn(b"OSError", stderr)

        # The same as the previous call, but with an empty handle_list
        handle_list = []
        startupinfo = subprocess.STARTUPINFO()
        startupinfo.lpAttributeList = {"handle_list": handle_list}
        p = subprocess.Popen([sys.executable, "-c",
                              "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
                             stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                             startupinfo=startupinfo, close_fds=True)
        stdout, stderr = p.communicate()
        self.assertEqual(p.returncode, 1)
        self.assertIn(b"OSError", stderr)

        # Check for a warning due to using handle_list and close_fds=False
        with support.check_warnings((".*overriding close_fds", RuntimeWarning)):
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.lpAttributeList = {"handle_list": handles[:]}
            p = subprocess.Popen([sys.executable, "-c",
                                  "import msvcrt; print(msvcrt.open_osfhandle({}, 0))".format(handles[0])],
                                 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                                 startupinfo=startupinfo, close_fds=False)
            stdout, stderr = p.communicate()
            self.assertEqual(p.returncode, 0) 
Example 80
Project: SublimeGerrit   Author: borysf   File: git.py    GNU General Public License v2.0 4 votes vote down vote up
def __init__(self, cmd, shell_cmd, env, listener, path="", shell=False):
        self.listener = listener

        startupinfo = None
        if os.name == "nt":
            startupinfo = subprocess.STARTUPINFO()
            startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW

        if path:
            old_path = os.environ["PATH"]
            os.environ["PATH"] = os.path.expandvars(path)

        proc_env = os.environ.copy()
        proc_env.update(env)
        for k, v in proc_env.items():
            proc_env[k] = os.path.expandvars(v)

        if shell_cmd and sys.platform == "win32":
            self.proc = subprocess.Popen(shell_cmd, stdout=subprocess.PIPE,
                stderr=subprocess.PIPE, startupinfo=startupinfo, env=proc_env, shell=True)
        elif shell_cmd and sys.platform == "darwin":
            self.proc = subprocess.Popen(["/bin/bash", "-l", "-c", shell_cmd], stdout=subprocess.PIPE,
                stderr=subprocess.PIPE, startupinfo=startupinfo, env=proc_env, shell=False)
        elif shell_cmd and sys.platform == "linux":
            self.proc = subprocess.Popen(["/bin/bash", "-c", shell_cmd], stdout=subprocess.PIPE,
                stderr=subprocess.PIPE, startupinfo=startupinfo, env=proc_env, shell=False)
        else:
            self.proc = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                stderr=subprocess.PIPE, startupinfo=startupinfo, env=proc_env, shell=shell)

        if path:
            os.environ["PATH"] = old_path

        th1 = th2 = False
        if self.proc.stdout:
            th1 = threading.Thread(target=self.read_stdout)
            th1.start()

        if self.proc.stderr:
            th2 = threading.Thread(target=self.read_stderr)
            th2.start()

        ThreadProgress(th1 or th2, 'Running `%s`  ' % (cmd or shell_cmd))