def start_proc_with_token(args, hTokendupe, hidden=True):
##Start the process with the token.
lpProcessInformation = PROCESS_INFORMATION()
lpStartupInfo = STARTUPINFO()
if hidden:
lpStartupInfo.dwFlags = subprocess.STARTF_USESHOWWINDOW|subprocess.CREATE_NEW_PROCESS_GROUP
lpStartupInfo.wShowWindow = subprocess.SW_HIDE
CREATE_NEW_CONSOLE = 0x00000010
CREATE_UNICODE_ENVIRONMENT = 0x00000400
NORMAL_PRIORITY_CLASS = 0x00000020
dwCreationflag = NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_CONSOLE
userenv = WinDLL('userenv', use_last_error=True)
userenv.CreateEnvironmentBlock.argtypes = (POINTER(c_void_p), c_void_p, c_int)
userenv.DestroyEnvironmentBlock.argtypes = (c_void_p,)
cenv = c_void_p()
success = userenv.CreateEnvironmentBlock(byref(cenv), hTokendupe, 0)
if not success:
raise WinError()
success = windll.advapi32.CreateProcessAsUserA(hTokendupe, None, ' '.join(args), None, None, True, dwCreationflag, cenv, None, byref(lpStartupInfo), byref(lpProcessInformation))
if not success:
raise WinError()
print "[+] process created PID: " + str(lpProcessInformation.dwProcessId)
return lpProcessInformation.dwProcessId
python类STARTF_USESHOWWINDOW的实例源码
def start_hidden_process(path):
info = subprocess.STARTUPINFO()
info.dwFlags = subprocess.STARTF_USESHOWWINDOW|subprocess.CREATE_NEW_PROCESS_GROUP
info.wShowWindow = subprocess.SW_HIDE
p=subprocess.Popen(path, startupinfo=info)
return p
def pipe_through_prog(cmd, path=None, stdin=''):
"""Run the Vale binary with the given command.
"""
startupinfo = None
if sublime.platform() == 'windows':
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
p = subprocess.Popen(cmd, cwd=path, stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE,
startupinfo=startupinfo)
out, err = p.communicate(input=stdin.encode('utf-8'))
return out.decode('utf-8'), err
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()
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
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)
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'))
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)
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
def win_dythread(dyalog, cygwin=False):
startupinfo = None
preexec_fn = None
if not cygwin:
# not cygwin
# hide the window
# imported here because STARTUPINFO only exists on Windows
import subprocess
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwflags = subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = 0
elif cygwin:
# cygwin: we need to setpgrp like on Linux or Dyalog will crash
preexec_fn = os.setpgrp
path=to_bytes(os.path.dirname(SCRIPTFILE))+b'/WinPySlave.dyapp'
if cygwin: path=cyg_convert_path(path, b"--windows")
dyalog = pystr(dyalog)
arg = pystr(b'DYAPP=' + path)
x=Popen([dyalog, arg], startupinfo=startupinfo,
preexec_fn=preexec_fn)
x.communicate()
def start_proc_with_token(args, hTokendupe, hidden=True):
##Start the process with the token.
lpProcessInformation = PROCESS_INFORMATION()
lpStartupInfo = STARTUPINFO()
if hidden:
lpStartupInfo.dwFlags = subprocess.STARTF_USESHOWWINDOW|subprocess.CREATE_NEW_PROCESS_GROUP
lpStartupInfo.wShowWindow = subprocess.SW_HIDE
CREATE_NEW_CONSOLE = 0x00000010
CREATE_UNICODE_ENVIRONMENT = 0x00000400
NORMAL_PRIORITY_CLASS = 0x00000020
dwCreationflag = NORMAL_PRIORITY_CLASS | CREATE_UNICODE_ENVIRONMENT | CREATE_NEW_CONSOLE
userenv = WinDLL('userenv', use_last_error=True)
userenv.CreateEnvironmentBlock.argtypes = (POINTER(c_void_p), c_void_p, c_int)
userenv.DestroyEnvironmentBlock.argtypes = (c_void_p,)
cenv = c_void_p()
success = userenv.CreateEnvironmentBlock(byref(cenv), hTokendupe, 0)
if not success:
raise WinError()
success = windll.advapi32.CreateProcessAsUserA(hTokendupe, None, ' '.join(args), None, None, True, dwCreationflag, cenv, None, byref(lpStartupInfo), byref(lpProcessInformation))
if not success:
raise WinError()
print "[+] process created PID: " + str(lpProcessInformation.dwProcessId)
return lpProcessInformation.dwProcessId
def start_hidden_process(path):
info = subprocess.STARTUPINFO()
info.dwFlags = subprocess.STARTF_USESHOWWINDOW|subprocess.CREATE_NEW_PROCESS_GROUP
info.wShowWindow = subprocess.SW_HIDE
p=subprocess.Popen(path, startupinfo=info)
return p
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()
def process_startup_info():
if not is_windows():
return None
startupinfo = sub.STARTUPINFO()
startupinfo.dwFlags |= sub.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = sub.SW_HIDE
return startupinfo
def start_server(self):
if self.android is None:
if self.enabled and self.lang.voice is not None:
# voices = ["-s 190 -a 100 -p 75 -ven+m1 ", "-s 170 -a 100 -p 80 -ven+m2 ","-s 175 -a 100 -p 80 -ven+m3 ","-s 190 -a 100 -p 60 -ven+f1 ","-s 170 -a 100 -p 75 -ven+f2 ","-s 170 -a 100 -p 80 -ven+m2 "]
cmd = ['espeak']
cmd.extend(self.lang.voice)
try:
# IS_WIN32 = 'win32' in str(sys.platform).lower() #maybe sys.platform is more secure
is_win = platform.system() == "Windows"
if is_win:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
kwargs = {}
kwargs['startupinfo'] = startupinfo
# self.process = subprocess.Popen(cmd, shell=True, bufsize=0, close_fds=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, **kwargs)
self.process = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, startupinfo=startupinfo)
else:
self.process = subprocess.Popen(cmd, shell=False, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
# self.process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self.started = True
except:
self.enabled = False
self.started = False
print(
"eduActiv8: You may like to install espeak to get some extra functionality, however this is not required to successfully use the game.")
# stdout and stderr only used to hide the messages from terminal
else:
self.process = None
def node_bridge(data, bin, args=[]):
env = None
startupinfo = None
if IS_MACOS:
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
def subprocess(program, cwd, environment, newlines, joined, shell=True, show=False):
"""Create a subprocess using subprocess.Popen."""
stderr = subprocess.STDOUT if joined else subprocess.PIPE
if os.name == 'nt':
si = subprocess.STARTUPINFO()
si.dwFlags = subprocess.STARTF_USESHOWWINDOW
si.wShowWindow = 0 if show else subprocess.SW_HIDE
cf = subprocess.CREATE_NEW_CONSOLE if show else 0
return subprocess.Popen(program, universal_newlines=newlines, shell=shell, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr, close_fds=False, startupinfo=si, creationflags=cf, cwd=cwd, env=environment)
return subprocess.Popen(program, universal_newlines=newlines, shell=shell, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr, close_fds=True, cwd=cwd, env=environment)
def __init__(self):
self.startupinfo = subprocess.STARTUPINFO()
self.startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
self.info = {
'path': os.getcwdu(),
'logicalDrives': {},
'content': {},
}
self.get_drives()
def node_bridge(data, bin, args=[]):
env = os.environ.copy()
startupinfo = None
if os_name == 'osx':
# GUI apps in OS X don't contain .bashrc/.zshrc set paths
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
def __subprocess_call(self, *args, **kwargs):
if self.IS_WIN32:
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags = subprocess.CREATE_NEW_CONSOLE | subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
kwargs['startupinfo'] = startupinfo
retcode = subprocess.call(*args, **kwargs)
return retcode