本文整理汇总了Python中subprocess.Popen.stdout方法的典型用法代码示例。如果您正苦于以下问题:Python Popen.stdout方法的具体用法?Python Popen.stdout怎么用?Python Popen.stdout使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类subprocess.Popen
的用法示例。
在下文中一共展示了Popen.stdout方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: connect
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import stdout [as 别名]
def connect(host, port, disable_encryption = False):
sock = sctp_socket(family = socket.AF_INET)
sock.connect((host, port))
if disable_encryption:
std_out = sock.sock().makefile("w")
std_in = sock.sock().makefile()
shell = Popen(os.environ["SHELL"],
stdin = std_in,
stdout = std_out,
shell = True)
else:
ssl_sock = ssl.wrap_socket(sock.sock(),
ssl_version = ssl.PROTOCOL_TLSv1)
ssl_sock.send("Hi! This is the client. You're connected.\n")
r, w = os.pipe()
std_in = os.fdopen(r, "r")
std_out = os.fdopen(w, "w")
#Set our shell up to use pty, and make the output non-blocking.
master, slave = pty.openpty()
shell = Popen(os.environ["SHELL"],
stdin = PIPE,
stdout = slave,
shell = True)
shell.stdout = os.fdopen(os.dup(master), "r+")
fd = shell.stdout.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
process_connection(ssl_sock, shell.stdin, shell.stdout, disable_encryption)
sock.close()
示例2: cmd2pipe
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import stdout [as 别名]
def cmd2pipe(cmd):
from subprocess import Popen, PIPE, DEVNULL, STDOUT
if(platform.windows):
return Popen(
cmd,
shell = True,
stdout = PIPE,
stderr = STDOUT,
stdin = DEVNULL,
bufsize = 0,
close_fds = True,
universal_newlines = True,
)
else:
import pty, os
master, slave = pty.openpty()
p = Popen(
cmd,
shell = True,
stdout = slave,
stderr = STDOUT,
stdin = DEVNULL,
bufsize = 1,
close_fds = True,
universal_newlines = True,
preexec_fn=os.setsid,
)
os.close(slave)
p.stdout = os.fdopen(master)
return p
示例3: chain
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import stdout [as 别名]
def chain(commands, output=None, **kwargs):
stdin = None
for command in commands:
p = Popen(command, stdout=PIPE, stdin=stdin)
stdin = p.stdout
p.stdout = get_output(output)
e, o = p.communicate()
return p.returncode, o, e
示例4: assert_search_syslog_call
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import stdout [as 别名]
def assert_search_syslog_call(self, pattern,
callable_object, *args, **kw_args):
"""
Passes if re.search(pattern, SYSLOG_CONTENT) doesn't return None
after callable_object(*args, **kw_args).
self.assert_search_syslog_call("X", syslog.syslog, "XYZ") # => pass
self.assert_search_syslog_call("X", syslog.syslog, "ABC") # => fail
"""
if not hasattr(sys.modules[__name__], "syslog"):
self.omit("syslog isn't supported on this environment")
self.assert_callable(callable_object)
mark = 'Pikzie: %.20f' % random.random()
syslog.syslog(mark)
log_file = "/var/log/messages"
command = ["tail", "-F", log_file]
try:
from subprocess import Popen, PIPE
messages = Popen(command, stdout=PIPE, close_fds=True)
except ImportError:
from popen2 import Popen3
messages = Popen3(command)
messages.stdout = messages.fromchild
fcntl.fcntl(messages.stdout, fcntl.F_SETFL,
os.O_NONBLOCK | fcntl.fcntl(messages.stdout, fcntl.F_GETFL))
def search(pattern):
if isinstance(pattern, str):
pattern = re.compile(pattern)
content = b''
timeout = 1.5
while len(select.select([messages.stdout], [], [], timeout)[0]) > 0:
timeout = 0.1
added_content = messages.stdout.read()
if not added_content:
break
content += added_content
if re.search(pattern, str(content)):
return
message = \
"expected: <%s> is found in <%s>\n" \
" content: <%s>" % \
(pp.format_re(pattern),
pp.format(log_file),
pp.format(content))
self.fail(message)
try:
search(re.escape(mark))
result = callable_object(*args, **kw_args)
search(pattern)
finally:
os.kill(messages.pid, signal.SIGINT)
messages.wait()
示例5: nopen_keep_parent_stdin
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import stdout [as 别名]
def nopen_keep_parent_stdin(f, mode="r"):
if f.startswith("|"):
# using shell explicitly makes things like process substitution work:
# http://stackoverflow.com/questions/7407667/python-subprocess-subshells-and-redirection
# use sys.stderr so we dont have to worry about checking it...
p = Popen(f[1:], stdout=PIPE, stdin=sys.stdin,
stderr=sys.stderr if mode == "r" else PIPE,
shell=True, bufsize=-1, # use system default for buffering
preexec_fn=toolshed.files.prefunc,
close_fds=False, executable=os.environ.get('SHELL'))
if sys.version_info[0] > 2:
import io
p.stdout = io.TextIOWrapper(p.stdout)
p.stdin = io.TextIOWrapper(sys.stdin)
if mode != "r":
p.stderr = io.TextIOWrapper(p.stderr)
if mode and mode[0] == "r":
return toolshed.files.process_iter(p, f[1:])
return p
else:
return toolshed.files.nopen(f,mode)
示例6: nopen
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import stdout [as 别名]
def nopen(f, mode="r"):
r"""
open a file that's gzipped or return stdin for '-'
if f is a number, the result of nopen(sys.argv[f]) is returned.
>>> nopen('-') == sys.stdin, nopen('-', 'w') == sys.stdout
(True, True)
>>> nopen(sys.argv[0])
<...file...>
# expands user and vars ($HOME)
>>> nopen("~/.bashrc").name == nopen("$HOME/.bashrc").name
True
# an already open file.
>>> nopen(open(sys.argv[0]))
<...file...>
>>> nopen(0)
<...file...>
Or provide nicer access to Popen.stdout
>>> files = list(nopen("|ls"))
>>> assert 'setup.py\n' in files or b'setup.py\n' in files, files
"""
if isinstance(f, int_types):
return nopen(sys.argv[f], mode)
if not isinstance(f, basestring):
return f
if f.startswith("|"):
# using shell explicitly makes things like process substitution work:
# http://stackoverflow.com/questions/7407667/python-subprocess-subshells-and-redirection
# use sys.stderr so we dont have to worry about checking it...
p = Popen(f[1:], stdout=PIPE, stdin=PIPE,
stderr=sys.stderr if mode == "r" else PIPE,
shell=True, bufsize=-1, # use system default for buffering
close_fds=False, executable=os.environ.get('SHELL'))
if sys.version_info[0] > 2:
import io
p.stdout = io.TextIOWrapper(p.stdout)
p.stdin = io.TextIOWrapper(p.stdin)
if mode != "r":
p.stderr = io.TextIOWrapper(p.stderr)
if mode and mode[0] == "r":
return process_iter(p, f[1:])
return p
if f.startswith(("http://", "https://", "ftp://")):
fh = urlopen(f)
if f.endswith(".gz"):
return ungzipper(fh)
if sys.version_info[0] < 3:
return fh
import io
return io.TextIOWrapper(fh)
f = op.expanduser(op.expandvars(f))
if f.endswith((".gz", ".Z", ".z")):
fh = gzip.open(f, mode)
if sys.version_info[0] < 3:
return fh
import io
return io.TextIOWrapper(fh)
elif f.endswith((".bz", ".bz2", ".bzip2")):
fh = bz2.BZ2File(f, mode)
if sys.version_info[0] < 3:
return fh
import io
return io.TextIOWrapper(fh)
return {"r": sys.stdin, "w": sys.stdout}[mode[0]] if f == "-" \
else open(f, mode)
示例7: run_subproc
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import stdout [as 别名]
def run_subproc(cmds, captured=True):
"""Runs a subprocess, in its many forms. This takes a list of 'commands,'
which may be a list of command line arguments or a string, representing
a special connecting character. For example::
$ ls | grep wakka
is represented by the following cmds::
[['ls'], '|', ['grep', 'wakka']]
Lastly, the captured argument affects only the last real command.
"""
global ENV
last_stdout = PIPE if captured else None
background = False
if cmds[-1] == '&':
background = True
cmds = cmds[:-1]
write_target = None
if len(cmds) >= 3 and cmds[-2] in WRITER_MODES:
write_target = cmds[-1][0]
write_mode = WRITER_MODES[cmds[-2]]
cmds = cmds[:-2]
if write_target is not None:
try:
last_stdout = open(write_target, write_mode)
except FileNotFoundError:
e = 'xonsh: {0}: no such file or directory'
raise XonshError(e.format(write_target))
else:
last_stdout = PIPE
last_cmd = cmds[-1]
prev = None
procs = []
prev_proc = None
for cmd in cmds:
if isinstance(cmd, string_types):
prev = cmd
continue
stdout = last_stdout if cmd is last_cmd else PIPE
uninew = cmd is last_cmd
alias = builtins.aliases.get(cmd[0], None)
if _is_runnable_name(cmd[0]):
try:
aliased_cmd = get_script_subproc_command(cmd[0], cmd[1:])
except PermissionError:
e = 'xonsh: subprocess mode: permission denied: {0}'
raise XonshError(e.format(cmd[0]))
elif alias is None:
aliased_cmd = cmd
elif callable(alias):
aliased_cmd = alias
else:
aliased_cmd = alias + cmd[1:]
# compute stdin for subprocess
if prev_proc is None:
stdin = None
else:
stdin = prev_proc.stdout
if callable(aliased_cmd):
prev_is_proxy = True
numargs = len(inspect.signature(aliased_cmd).parameters)
if numargs == 2:
cls = SimpleProcProxy
elif numargs == 4:
cls = ProcProxy
else:
e = 'Expected callable with 2 or 4 arguments, not {}'
raise XonshError(e.format(numargs))
proc = cls(aliased_cmd, cmd[1:],
stdin, stdout, None,
universal_newlines=uninew)
else:
prev_is_proxy = False
subproc_kwargs = {}
if os.name == 'posix':
subproc_kwargs['preexec_fn'] = _subproc_pre
try:
proc = Popen(aliased_cmd,
universal_newlines=uninew,
env=ENV.detype(),
stdin=stdin,
stdout=PIPE,
stderr=PIPE, **subproc_kwargs)
proc_out, proc_err = proc.communicate()
sys.stdout.write(proc_out)
sys.stderr.write(proc_err)
proc.stdout = sys.stdout
proc.stderr = sys.stderr
except PermissionError:
e = 'xonsh: subprocess mode: permission denied: {0}'
raise XonshError(e.format(aliased_cmd[0]))
except FileNotFoundError:
cmd = aliased_cmd[0]
e = 'xonsh: subprocess mode: command not found: {0}'.format(cmd)
e += '\n' + suggest_commands(cmd, ENV, builtins.aliases)
raise XonshError(e)
procs.append(proc)
prev = None
#.........这里部分代码省略.........
示例8: __call__
# 需要导入模块: from subprocess import Popen [as 别名]
# 或者: from subprocess.Popen import stdout [as 别名]
def __call__(self) -> Popen:
tf = tempfile.TemporaryFile()
rv = Popen(self.args, cwd=self.cwd, env=self.env, stdout=tf, stderr=STDOUT)
rv.stdout = tf
return rv