本文整理汇总了Python中subprocess32.Popen.communicate方法的典型用法代码示例。如果您正苦于以下问题:Python Popen.communicate方法的具体用法?Python Popen.communicate怎么用?Python Popen.communicate使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类subprocess32.Popen
的用法示例。
在下文中一共展示了Popen.communicate方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import communicate [as 别名]
def run():
is_timeout = False
code = request.form.get('code')
stdin = request.form.get('stdin')
code_filename = "/tmp/" + str(uuid4())
try:
with open(code_filename, "w") as code_file:
code_file.write(code)
p = Popen(
['bbm', code_filename],
stdout=PIPE,
stdin=PIPE,
stderr=PIPE
)
stdout, stderr = p.communicate(input=stdin.encode('utf-8'), timeout=15)
except TimeoutExpired:
is_timeout = True
p.kill()
stdout, stderr = p.communicate()
finally:
remove(code_filename)
stdout = stdout.decode('utf-8')
stderr = stderr.decode('utf-8')
return jsonify({
'stdout': stdout,
'stderr': stderr,
'is_timeout': is_timeout
})
示例2: DummySim
# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import communicate [as 别名]
class DummySim(ProcessWorkerThread):
def handle_eval(self, record):
# This gives a file name / directory name that no other thread can use
my_unique_filename = my_gen.next_filename()
my_unique_filename = str(my_unique_filename) + ".txt"
# Print to the input file
f = open(my_unique_filename, 'w')
f.write(array2str(record.params[0]))
f.close()
# Run the objective function and pass the filename of the input file
self.process = Popen(['./sphere_ext_files', my_unique_filename], stdout=PIPE)
out = self.process.communicate()[0]
# Parse the output
try:
val = float(out) # This raises ValueError if out is not a float
self.finish_success(record, val)
os.remove(my_unique_filename) # Remove input file
except ValueError:
logging.warning("Function evaluation crashed/failed")
self.finish_failure(record)
os.remove(my_unique_filename) # Remove input file
示例3: check_container_status_rkt
# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import communicate [as 别名]
def check_container_status_rkt():
"""
Checks and prints the calico/node container status when running in rkt.
"""
list_cmd = ["sudo", "rkt", "list"]
p = Popen(list_cmd, stdin=PIPE, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
containers = RKT_CONTAINER_RE.findall(stdout)
if p.returncode:
print "Unable to list rkt containers: '%s'" % stderr.strip()
sys.exit(1)
if len(containers) == 0:
print "calico-node container not running"
sys.exit(1)
else:
# Get statuses for all calico/node containers, and determine
# if any are running.
statuses = [c[2] for c in containers]
running = "running" in statuses
# If one is running, status is "running". Else, use the status of
# the first container.
status = "running" if running else statuses[0]
# Print status. If it at least one is running, this will display
# "running" status.
print "calico-node container status: %s" % status
示例4: run_judge_client
# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import communicate [as 别名]
def run_judge_client(self):
self.copy_assets()
args = ["python", os.path.realpath('judge-client.py'), './attacker', './defender']
self.log += ['Running: ' + ' '.join(args)]
proc = Popen(args, cwd=self.base_dir, stdin=PIPE, stdout=PIPE, stderr=PIPE)
output = proc.communicate()
self.log += [str(output[1])]
if proc.returncode:
self.log += ["Judge client crashed with return code %d." % proc.returncode]
raise JudgeClientException("judge client crashed.")
result = output[0].split('\n')
winner = result[0]
if winner == "attacker":
self.record.attacker_wins()
elif winner == "defender":
self.record.defender_wins()
else:
self.log += ["Judge client return unknown winner %s." % winner]
raise JudgeClientException("unknown winner.")
reason = result[1]
if reason == "Finished":
self.record.status = ExecutionRecord.STATUS_FINISHED
elif reason == "IllegalMovement":
self.record.status = ExecutionRecord.STATUS_ILLEGAL_MOVE
elif reason == "IllegalOutput":
self.record.status = ExecutionRecord.STATUS_BAD_FORMAT
elif reason == "TLE":
self.record.status = ExecutionRecord.STATUS_TLE
elif reason == "Crashed":
self.record.status = ExecutionRecord.STATUS_RUNTIME_ERROR
else:
self.log += ["Judge client return unknown reason %s." % reason]
raise JudgeClientException("unknown reason.")
self.record.replay = result[2:]
示例5: process
# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import communicate [as 别名]
def process(self, json_data, namedblobfile=None):
tmpdir_path = tempfile.mkdtemp(prefix='opengever.core.sablon_')
output_path = join(tmpdir_path, 'sablon_output.docx')
if namedblobfile is None:
template_path = self.template.as_file(tmpdir_path)
else:
template_path = join(tmpdir_path, namedblobfile.filename)
with open(template_path, 'wb') as template_file:
template_file.write(namedblobfile.data)
try:
sablon_path = environ.get('SABLON_BIN', 'sablon')
subprocess = Popen(
[sablon_path, template_path, output_path],
stdin=PIPE, stdout=PIPE, stderr=PIPE)
self.stdout, self.stderr = subprocess.communicate(input=json_data)
self.returncode = subprocess.returncode
if not self.is_processed_successfully():
raise SablonProcessingFailed(self.stderr)
with open(output_path, 'rb') as outfile:
self.file_data = outfile.read()
finally:
shutil.rmtree(tmpdir_path)
return self
示例6: install_dropbox_helper
# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import communicate [as 别名]
def install_dropbox_helper(package = None, fullpath = None, tmp = False):
if not os.path.exists(HELPER_INSTALLER_PATH):
raise InstallError('no installer')
assert package or fullpath
if not fullpath:
fullpath = get_package_location(package)
TRACE('Installing %s', package or fullpath)
cmd = 'install-tmp' if tmp else 'install'
p = Popen([HELPER_INSTALLER_PATH,
cmd,
BUILD_KEY,
fullpath], stdout=PIPE, stderr=PIPE)
out, err = p.communicate()
if p.returncode != 0:
if out:
TRACE('stdout: %s', out)
if err:
TRACE('stderr: %s', err)
raise InstallError('Installer returned %d' % p.returncode)
if tmp:
path = None
for l in out.split('\n'):
m = re.match('\\<path\\>(?P<path>.+)\\</path\\>', l)
if m:
path = m.group('path')
if path:
return os.path.join(path, REL_HELPERS_DIR)
raise InstallError('no path')
示例7: invoke_side_effects
# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import communicate [as 别名]
def invoke_side_effects(argv):
log("invoke_side_effects: %s"
% ' '.join(sys.argv))
gccinv = GccInvocation(argv)
# Try to run each side effect in a subprocess, passing in a path
# for the XML results to be written to.
# Cover a multitude of possible failures by detecting if no output
# was written, and capturing *that* as a failure
for sourcefile in gccinv.sources:
if sourcefile.endswith('.c'): # FIXME: other extensions?
for script, genname in [('invoke-cppcheck', 'cppcheck'),
('invoke-clang-analyzer', 'clang-analyzer'),
('invoke-cpychecker', 'cpychecker'),
# Uncomment the following to test a
# checker that fails to write any XML:
# ('echo', 'failing-checker'),
]:
with tempfile.NamedTemporaryFile() as f:
dstxmlpath = f.name
assert not os.path.exists(dstxmlpath)
# Restrict the invocation to just one source file at a
# time:
singleinv = gccinv.restrict_to_one_source(sourcefile)
singleargv = singleinv.argv
TIMEOUT=60
t = Timer()
args = [script, dstxmlpath] + singleargv
log('invoking args: %r' % args)
p = Popen(args,
stdout=PIPE, stderr=PIPE)
try:
out, err = p.communicate(timeout=TIMEOUT)
write_streams(script, out, err)
if os.path.exists(dstxmlpath):
with open(dstxmlpath) as f:
analysis = Analysis.from_xml(f)
else:
analysis = make_failed_analysis(genname, sourcefile, t,
msgtext=('Unable to locate XML output from %s'
% script),
failureid='no-output-found')
analysis.set_custom_field('stdout', out)
analysis.set_custom_field('stderr', err)
analysis.set_custom_field('returncode', p.returncode)
except TimeoutExpired:
analysis = make_failed_analysis(genname, sourcefile, t,
msgtext='Timeout running %s' % genname,
failureid='timeout')
analysis.set_custom_field('timeout', TIMEOUT)
analysis.set_custom_field('gcc-invocation', ' '.join(argv))
write_analysis_as_xml(analysis)
示例8: DummySim
# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import communicate [as 别名]
class DummySim(ProcessWorkerThread):
def handle_eval(self, record):
self.process = Popen(['./sphere_ext', array2str(record.params[0])],
stdout=PIPE)
out = self.process.communicate()[0]
try:
val = float(out) # This raises ValueError if out is not a float
self.finish_success(record, val)
except ValueError:
logging.warning("Function evaluation crashed/failed")
self.finish_failure(record)
示例9: check_output
# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import communicate [as 别名]
def check_output(*popenargs, **kwargs):
r"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n'
"""
timeout = kwargs.pop('timeout', None)
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
if _kill_processes.is_set():
raise TerminateSignaled()
process = Popen(stdout=PIPE, *popenargs, **kwargs)
_processes.append(process)
try:
output, unused_err = process.communicate(timeout=timeout)
_processes.remove(process)
except TimeoutExpired:
_processes.remove(process)
process.kill()
output, unused_err = process.communicate()
raise TimeoutExpired(process.args, timeout, output=output)
retcode = process.poll()
if retcode:
raise CalledProcessError(retcode, process.args, output=output)
return output
示例10: run
# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import communicate [as 别名]
def run(self):
'''
Execute a module as a bash command. Open handles file object as input.
Log output and/or errors.
'''
command = self.bake_command()
try:
process = Popen(command,
stdin=self.streams['input'],
stdout=self.streams['output'],
stderr=self.streams['error'])
# Prepare handles input.
input_data = None
if self.streams['input'] == PIPE:
input_data = open(self.handles).readlines()
# We have to provide the temporary filename to the modules.
i = -1
for line in input_data:
i = i + 1
# Replace the value of the 'hdf5_filename' key.
# Doing this via YAML should be saver.
if re.match('hdf5_filename', line):
hdf5_key = yaml.load(line)
hdf5_key['hdf5_filename'] = self.tmp_filename
input_data[i] = yaml.dump(hdf5_key,
default_flow_style=False)
# Create the new handles string.
input_data = ''.join(input_data)
# Execute sub-process.
(stdoutdata, stderrdata) = process.communicate(input=input_data)
# Write output and errors if 'logging' is requested by user
if self.logging_level is not None:
self.write_output_and_errors(stdoutdata, stderrdata)
# Modify for nicer output to command line.
ignore_list = ['INFO:']
if any([re.search(x, stderrdata) for x in ignore_list]):
newstderrdata = str()
for line in stderrdata.split('\n'):
if not any([re.search(x, line) for x in ignore_list]):
newstderrdata = newstderrdata + line
stderrdata = newstderrdata
print stdoutdata
print stderrdata
# Close STDIN file descriptor.
process.stdin.close
# Take care of any errors during the execution.
if process.returncode > 0 or re.search('Error', stderrdata):
raise JteratorError(self.get_error_message(process,
input_data, stdoutdata, stderrdata))
except ValueError as error:
raise JteratorError('Failed running \'%s\'. Reason: \'%s\'' %
(command, str(error)))
示例11: invoke_real_executable
# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import communicate [as 别名]
def invoke_real_executable(argv):
args = [get_real_executable(argv)] + argv[1:]
if 0:
log(' '.join(args))
p = Popen(args, stderr=PIPE)
try:
t = Timer()
out, err = p.communicate()
sys.stderr.write(err)
parse_gcc_stderr(err,
stats=make_stats(t))
except KeyboardInterrupt:
pass
return p.returncode
示例12: run
# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import communicate [as 别名]
def run(self, *args, **kwargs):
if self.path is not None:
# only None when called in the __init__ function
kwargs.setdefault("cwd", self.path)
# NOTE if we do want to make a copy of environmental variables,
# we must remove GIT_WORK_TREE
kwargs["env"] = {}
kwargs["stdout"] = PIPE
kwargs["stderr"] = PIPE
proc = Popen(args, **kwargs)
(stdout, stderr) = proc.communicate()
if proc.returncode != 0:
raise CommandError(args[0], proc.returncode, stdout, stderr)
return stdout
示例13: run_compiler
# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import communicate [as 别名]
def run_compiler(self, language, filename, executable_name):
args = ["g++" if language else "gcc", "-static", "-w", "-O2", filename, "-o",
executable_name]
self.log += ['Running: ' + ' '.join(args)]
proc = Popen(args,
cwd=self.base_dir, stdin=PIPE, stdout=PIPE, stderr=PIPE)
output = proc.communicate(timeout=self.COMPILE_TIMEOUT)
self.log += [str(output[1])]
if proc.poll() is None:
try:
self.log += ['Compile timeout.']
proc.kill()
except Exception:
pass
self.log += ["Compiler returns %d." % proc.returncode]
if proc.returncode:
raise CompileErrorException()
示例14: clone
# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import communicate [as 别名]
def clone(cls, remote_url, path):
"""Clone the remote and return a GitVcs object pointed at the new repo.
:param str remote_url: the URL to clone from
:param str path: path to clone to
:rtype: GitVcs
:returns: a GitVcs object for the new cloned repo
:raises tigerhost.vcs.base.CommandError:
"""
args = ['git', 'clone', '--recursive', remote_url, path]
proc = Popen(args, stdout=PIPE, stderr=PIPE)
(stdout, stderr) = proc.communicate()
if proc.returncode != 0:
raise CommandError(args[0], proc.returncode, stdout, stderr)
return cls(path=path)
示例15: stop
# 需要导入模块: from subprocess32 import Popen [as 别名]
# 或者: from subprocess32.Popen import communicate [as 别名]
def stop(self, job, msg, exit_code):
"""
Stop running job and remove it from PBS queue.
:param job: :py:class:`Job` instance
:param msg: Message that will be passed to the user
"""
_pbs_id = ''
# Get Job PBS ID
try:
_pbs_id = str(job.scheduler.id)
except:
job.die('@PBS - Unable to read PBS job ID', exc_info=True)
return
# Run qdel
logger.debug("@PBS - Killing job")
# @TODO Seperate users for each sevice
# Run qdel with proper user permissions
# _user = self.jm.services[job.service].config['username']
# _comm = "/usr/bin/qdel %s" % _pbs_id
# _sudo = "/usr/bin/sudo /bin/su -c \"%s\" %s" % (_comm, _user)
# _opts = ['/usr/bin/ssh', '-t', '-t', 'local', _sudo]
_opts = ['/usr/bin/qdel', '-b', str(conf.pbs_timeout), _pbs_id]
logger.log(VERBOSE, "@PBS - Running command: %s", _opts)
_proc = Popen(_opts, stdout=PIPE, stderr=STDOUT)
_output = _proc.communicate()[0]
logger.log(VERBOSE, _output)
# Check return code. If qdel was not killed by signal Popen will
# not rise an exception
# @TODO handle temporary communication timeouts with pbs server
if _proc.returncode == 170: # Job in wrong state (e.g. exiting)
logger.debug("@PBS - Wait with job kill: /usr/bin/qdel "
"returned 170 exit code (%s)", _output)
raise CisError("PBS qdel wrong job state")
if _proc.returncode != 0:
raise OSError((
_proc.returncode,
"/usr/bin/qdel returned non zero exit code.\n%s" %
str(_output)
))
# Mark as killed by user
job.mark(msg, exit_code)