本文整理汇总了Python中subprocess32.Popen方法的典型用法代码示例。如果您正苦于以下问题:Python subprocess32.Popen方法的具体用法?Python subprocess32.Popen怎么用?Python subprocess32.Popen使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类subprocess32
的用法示例。
在下文中一共展示了subprocess32.Popen方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: exec_command
# 需要导入模块: import subprocess32 [as 别名]
# 或者: from subprocess32 import Popen [as 别名]
def exec_command(cmd, args, cwd, timeout=None):
"""
Executes shell command inside @repo_path
returns exec code
"""
pipe = None
try:
env = os.environ
env["PATH"] = env["NDK_TOOLCHAIN"] + "/bin:" + env["PATH"]
pipe = Popen(args, stdin=PIPE, stdout=PIPE, cwd=cwd, env=env)
stdout, error = pipe.communicate(timeout=timeout) if (timeout and timeout > 0) else pipe.communicate()
logger.debug("stdout: %s", stdout)
return pipe.returncode
except TimeoutExpired as te:
pipe.terminate()
logger.error("%s timed out: %s", cmd, str(te))
return 0
except Exception as e:
logger.error("%s subprocess failed: %s", cmd, str(e))
return -1
示例2: run_cmd
# 需要导入模块: import subprocess32 [as 别名]
# 或者: from subprocess32 import Popen [as 别名]
def run_cmd(cmd):
c = cmd[:-1]
timeout = cmd[-1]
display("Executing command: %s" % " ".join(c))
current_time = time.time()
if timeout:
process = Popen(c)
while time.time() < current_time + timeout and process.poll() is None:
time.sleep(5)
if process.poll() is None:
display_error(
"Timeout of %s reached. Aborting thread for command: %s"
% (timeout, " ".join(c))
)
process.terminate()
else:
Popen(c).wait()
return cmd
示例3: open_process
# 需要导入模块: import subprocess32 [as 别名]
# 或者: from subprocess32 import Popen [as 别名]
def open_process(cls, cmd, **kwargs):
"""Opens a process object via subprocess.Popen().
:param string|list cmd: A list or string representing the command to run.
:param **kwargs: Additional kwargs to pass through to subprocess.Popen.
:return: A `subprocess.Popen` object.
:raises: `Executor.ExecutableNotFound` when the executable requested to run does not exist.
"""
assert len(cmd) > 0, 'cannot execute an empty command!'
try:
return subprocess.Popen(cmd, **kwargs)
except (IOError, OSError) as e:
if e.errno == errno.ENOENT:
raise cls.ExecutableNotFound(cmd, e)
else:
raise cls.ExecutionError(repr(e), cmd, e)
示例4: execute
# 需要导入模块: import subprocess32 [as 别名]
# 或者: from subprocess32 import Popen [as 别名]
def execute(cls, cmd, stdin_payload=None, **kwargs):
"""Execute a command via subprocess.Popen and returns the stdio.
:param string|list cmd: A list or string representing the command to run.
:param string stdin_payload: A string representing the stdin payload, if any, to send.
:param **kwargs: Additional kwargs to pass through to subprocess.Popen.
:return: A tuple of strings representing (stdout, stderr), pre-decoded for utf-8.
:raises: `Executor.ExecutableNotFound` when the executable requested to run does not exist.
`Executor.NonZeroExit` when the execution fails with a non-zero exit code.
"""
process = cls.open_process(cmd=cmd,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
**kwargs)
stdout_raw, stderr_raw = process.communicate(input=stdin_payload)
# N.B. In cases where `stdout` or `stderr` is passed as parameters, these can be None.
stdout = stdout_raw.decode('utf-8') if stdout_raw is not None else stdout_raw
stderr = stderr_raw.decode('utf-8') if stderr_raw is not None else stderr_raw
if process.returncode != 0:
raise cls.NonZeroExit(cmd, process.returncode, stdout, stderr)
return stdout, stderr
示例5: command
# 需要导入模块: import subprocess32 [as 别名]
# 或者: from subprocess32 import Popen [as 别名]
def command(cmd, *arguments, **options):
close_fds = options.get('close_fds', True)
cwd = options.get('cwd', None)
shell = options.get('shell', False)
env = options.get('env', None)
if env is not None:
env = dict(os.environ, **env)
stdin = options.get('stdin', None)
subproc = subprocess32.Popen([cmd] + list(arguments),
close_fds=close_fds,
shell=shell,
cwd=cwd,
env=env,
stdin=subprocess32.PIPE,
stdout=subprocess32.PIPE,
stderr=subprocess32.PIPE, )
out, err = subproc.communicate(input=stdin)
subproc.wait()
return (subproc.returncode, out, err)
示例6: subproc
# 需要导入模块: import subprocess32 [as 别名]
# 或者: from subprocess32 import Popen [as 别名]
def subproc(script, cwd=None):
subproc = subprocess32.Popen(['sh'],
close_fds=True,
cwd=cwd,
stdin=subprocess32.PIPE,
stdout=subprocess32.PIPE,
stderr=subprocess32.PIPE)
out, err = subproc.communicate(script)
subproc.wait()
if subproc.returncode != 0:
print out
print err
return (subproc.returncode, out, err)
示例7: start_worker
# 需要导入模块: import subprocess32 [as 别名]
# 或者: from subprocess32 import Popen [as 别名]
def start_worker(node_ip_address, worker_path, scheduler_address, objstore_address=None, cleanup=True):
"""This method starts a worker process.
Args:
node_ip_address (str): The IP address of the node that the worker runs on.
worker_path (str): The path of the source code which the worker process will
run.
scheduler_address (str): The ip address and port of the scheduler to connect
to.
objstore_address (Optional[str]): The ip address and port of the object
store to connect to.
cleanup (Optional[bool]): True if using Ray in local mode. If cleanup is
true, then this process will be killed by serices.cleanup() when the
Python process that imported services exits. This is True by default.
"""
command = ["python",
worker_path,
"--node-ip-address=" + node_ip_address,
"--scheduler-address=" + scheduler_address]
if objstore_address is not None:
command.append("--objstore-address=" + objstore_address)
p = subprocess.Popen(command)
if cleanup:
all_processes.append(p)
示例8: ensure_terminated
# 需要导入模块: import subprocess32 [as 别名]
# 或者: from subprocess32 import Popen [as 别名]
def ensure_terminated(self, status=""):
if self._popen:
try:
os.kill(self._popen.pid, signal.SIGINT)
except OSError:
print "Process does not exist"
return
time.sleep(0.5)
if self._popen:
self._popen.poll()
if self._popen.returncode is None:
self._popen.terminate()
time.sleep(0.2)
self._popen.poll()
while self._popen.returncode is None:
time.sleep(1)
if status:
print(status)
self._popen.poll()
else:
print "ERROR Popen is NONE"
示例9: open_process
# 需要导入模块: import subprocess32 [as 别名]
# 或者: from subprocess32 import Popen [as 别名]
def open_process(command, cwd=None, shell=True, _popen_lock=threading.Lock()):
kwargs = {
"shell": shell,
"stdout": subprocess.PIPE,
"stderr": subprocess.STDOUT,
"stdin": subprocess.PIPE,
"bufsize": 1, # Line buffered
"universal_newlines": True,
}
if cwd is not None:
kwargs["cwd"] = cwd
# Prevent signal propagation from parent process
try:
# Windows
kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP
except AttributeError:
# Unix
kwargs["preexec_fn"] = os.setpgrp
with _popen_lock: # Work around Python 2 Popen race condition
return subprocess.Popen(command, **kwargs)
示例10: xvfb_supports_listen
# 需要导入模块: import subprocess32 [as 别名]
# 或者: from subprocess32 import Popen [as 别名]
def xvfb_supports_listen():
"""Determine whether the '-listen' option is supported by Xvfb."""
p = subprocess.Popen(
['Xvfb', '-listen', 'TCP', '-__sentinel_parameter__'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
p.wait()
_, stderr = p.communicate()
match = re.search(
br'^Unrecognized option: (?P<option>.*)$',
stderr,
flags=re.MULTILINE,
).groupdict()
unrecognized_option = match['option']
return unrecognized_option != b'-listen'
示例11: check_output
# 需要导入模块: import subprocess32 [as 别名]
# 或者: from subprocess32 import Popen [as 别名]
def check_output(*popenargs, **kwargs):
"""Run command with arguments and return its output (both stdout and stderr) as a byte string.
If the exit code was non-zero it raises a CalledProcessWithOutputError.
"""
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
if 'stderr' in kwargs:
raise ValueError('stderr argument not allowed, it will be overridden.')
process = subprocess.Popen(
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
*popenargs, **kwargs)
output, err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessWithOutputError(retcode, cmd, output, err)
return output, err
示例12: run_in_subprocess
# 需要导入模块: import subprocess32 [as 别名]
# 或者: from subprocess32 import Popen [as 别名]
def run_in_subprocess(cmd, check_output=False, **kwargs):
"""
Execute command using default subprocess configuration.
Parameters
----------
cmd : string
Command to be executed in subprocess.
kwargs : keywords
Options to pass to subprocess.Popen.
Returns
-------
proc : Popen subprocess
Subprocess used to run command.
"""
logger.debug('Executing command: {0}'.format(cmd))
config = DEFAULT_SUBPROCESS_CONFIG.copy()
config.update(kwargs)
if not check_output:
if omniduct_config.logging_level < 20:
config['stdout'] = None
config['stderr'] = None
else:
config['stdout'] = open(os.devnull, 'w')
config['stderr'] = open(os.devnull, 'w')
timeout = config.pop('timeout', None)
process = subprocess.Popen(cmd, **config)
try:
stdout, stderr = process.communicate(None, timeout=timeout)
except subprocess.TimeoutExpired:
os.killpg(os.getpgid(process.pid), signal.SIGINT) # send signal to the process group, recursively killing all children
output, unused_err = process.communicate()
raise subprocess.TimeoutExpired(process.args, timeout, output=output)
return SubprocessResults(returncode=process.returncode, stdout=stdout or b'', stderr=stderr or b'')
示例13: run_cmd_noout
# 需要导入模块: import subprocess32 [as 别名]
# 或者: from subprocess32 import Popen [as 别名]
def run_cmd_noout(cmd_data):
cmd = cmd_data[0]
output = cmd_data[1]
c = cmd[:-1]
timeout = cmd[-1]
display("Executing command: %s" % " ".join(c))
current_time = time.time()
f = open(output, 'w')
if timeout:
process = Popen(c, stdout=f, stderr=STDOUT)
while time.time() < current_time + timeout and process.poll() is None:
time.sleep(5)
if process.poll() is None:
display_error(
"Timeout of %s reached. Aborting thread for command: %s"
% (timeout, " ".join(c))
)
process.terminate()
else:
Popen(c, stdout=f, stderr=STDOUT).wait()
f.close()
return cmd_data
示例14: run_proc_with_quit
# 需要导入模块: import subprocess32 [as 别名]
# 或者: from subprocess32 import Popen [as 别名]
def run_proc_with_quit(proc_id, quit_dict, args, logfile=None, append=False, env=None, cwd=None):
if logfile is None:
logfile = os.devnull
mode = 'ab' if append else 'wb'
with open(logfile, mode) as logf:
if proc_id in quit_dict:
return None
proc = subprocess.Popen(args, stdout=logf, stderr=subprocess.STDOUT,
env=env, cwd=cwd)
retcode = None
num_kill = 0
timeout = 0.05
while retcode is None and num_kill <= 2:
try:
retcode = proc.wait(timeout=timeout)
except subprocess.TimeoutExpired:
if proc_id in quit_dict:
if num_kill == 0:
proc.terminate()
timeout = quit_dict[proc_id]
elif num_kill == 1:
proc.kill()
num_kill += 1
return proc.returncode
示例15: test_stdin_stdout
# 需要导入模块: import subprocess32 [as 别名]
# 或者: from subprocess32 import Popen [as 别名]
def test_stdin_stdout(self):
proc = subprocess32.Popen(
(sys.executable, '-m', 'pykit.p3json.tool'),
stdin=subprocess32.PIPE, stdout=subprocess32.PIPE)
out, err = proc.communicate(self.data.encode())
self._assert_expected(out, linemode=True)
self.assertEqual(err, None)