def index():
if request.args.get('code'):
unlock_code = request.args.get('code')
# unlock, new password
re = s.query(RecoveryEmail).filter(RecoveryEmail.password_code==unlock_code).one_or_none()
if re:
jid = re.jid
re.password_code = None
s.merge(re)
s.commit()
# set new password and send email
email_address = re.email
password = ''.join(random.SystemRandom().choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(10))
p = subprocess.Popen(['/usr/bin/prosodyctl', 'passwd', jid], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
args = bytes("%s\n%s\n" % (password, password), encoding='utf8')
p.communicate(args)
sendMail(email_address, 'new password', password)
content = render_template('success.html', message='password was sent')
else:
content = render_template('error.html', message='link invalid')
else:
content = render_template('index.html')
return content
python类Popen()的实例源码
def _download_packages(self):
if not os.path.exists(self.args[0]):
os.makedirs(self.args[0])
for package, pkg_opts in self.packages.iteritems():
target = '%s/%s' % (self.mirror, pkg_opts['Filename'])
debfilename = os.path.basename(target)
local_debfile_path = os.path.join(self.args[0], debfilename)
print 'Processing.. %s' % target
if os.path.exists(local_debfile_path):
md5sum = md5_checksum(local_debfile_path)
if md5sum == pkg_opts['MD5sum']:
print ' . skipping... (MD5sum match)'
continue
print " . downloading..."
proc = subprocess.Popen(['wget', '-nv', '-P', self.args[0], target])
proc.communicate()
def output_articles(articles):
if len(articles) == 0:
print('No articles found')
return
try:
pager = subprocess.Popen(['less'],
stdin=subprocess.PIPE,
stdout=sys.stdout)
for article in articles:
if int(article['reading_time']) <= 0:
article['reading_time'] = 'Unknown'
content = format_article(article, line=True)
if six.PY3:
content = bytearray(content, 'utf-8')
pager.stdin.write(content)
pager.stdin.close()
pager.wait()
except (KeyboardInterrupt, ValueError):
pass
def run_coala_with_specific_file(working_dir, file):
"""Run coala in a specified directory."""
command = ["coala", "--json", "--find-config", "--files", file]
stdout_file = tempfile.TemporaryFile()
kwargs = {"stdout": stdout_file,
"cwd": working_dir}
process = subprocess.Popen(command, **kwargs)
retval = process.wait()
output_str = None
if retval == 1:
stdout_file.seek(0)
output_str = stdout_file.read().decode("utf-8", "ignore")
if output_str:
log("Output =", output_str)
else:
log("No results for the file")
elif retval == 0:
log("No issues found")
else:
log("Exited with:", retval)
stdout_file.close()
return output_str
def spawn(self, cmd, stdin_content="", stdin=False, shell=False, timeout=2):
"""
Spawn a new process using subprocess
"""
try:
if type(cmd) != list:
raise PJFInvalidType(type(cmd), list)
if type(stdin_content) != str:
raise PJFInvalidType(type(stdin_content), str)
if type(stdin) != bool:
raise PJFInvalidType(type(stdin), bool)
self._in = stdin_content
try:
self.process = subprocess.Popen(cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, shell=shell)
self.finish_read(timeout, stdin_content, stdin)
if self.process.poll() is not None:
self.close()
except KeyboardInterrupt:
return
except OSError:
raise PJFProcessExecutionError("Binary <%s> does not exist" % cmd[0])
except Exception as e:
raise PJFBaseException(e.message if hasattr(e, "message") else str(e))
def spawn(self, lines, additional_args = [ '-p', ''], width = None):
(mouse_x, mouse_y) = get_mouse_location()
if not width:
width = 100 # some default width
width = max(width, 101) # width has to be 100 at least (rofi restriction)
# first, compute the top left corner of the menu
menu_x = min(max(mouse_x - width/2, self.x), self.x + self.panel_width - width)
menu_y = self.y
# then, specify these coordinates relative to the mouse cursor
menu_x -= mouse_x
menu_y -= mouse_y
# compile rofi arguments
cmd = ['rofi', '-dmenu', '-sep' , '\\0' ]
cmd += ['-monitor', '-3' ] # position relative to mouse cursor
cmd += ['-layout', '1' ] # specify top left corner of the menu
cmd += ['-width', str(width) ]
cmd += ['-xoffset', str(menu_x), '-yoffset', str(menu_y) ]
cmd += self.rofi_args
cmd += additional_args
rofi = subprocess.Popen(cmd,stdout=subprocess.PIPE,stdin=subprocess.PIPE)
for i in lines:
rofi.stdin.write(i.encode('utf-8'))
rofi.stdin.write(struct.pack('B', 0))
rofi.stdin.close()
rofi.wait()
def communicate(input, coro=None):
if platform.system() == 'Windows':
# asyncfile.Popen must be used instead of subprocess.Popen
pipe = asyncoro.asyncfile.Popen([r'\cygwin64\bin\sha1sum.exe'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
else:
pipe = subprocess.Popen(['sha1sum'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# convert pipe to asynchronous version
async_pipe = asyncoro.asyncfile.AsyncPipe(pipe)
# 'communicate' takes either the data or file descriptor with data
# (if file is too large to read in full) as input
input = open(input)
stdout, stderr = yield async_pipe.communicate(input)
print('communicate sha1sum: %s' % stdout)
def custom_feeder(input, coro=None):
def write_proc(fin, pipe, coro=None):
while True:
data = yield os.read(fin.fileno(), 8*1024)
if not data:
break
n = yield pipe.write(data, full=True)
assert n == len(data)
fin.close()
pipe.stdin.close()
def read_proc(pipe, coro=None):
# output from sha1sum is small, so read until EOF
data = yield pipe.stdout.read()
pipe.stdout.close()
raise StopIteration(data)
if platform.system() == 'Windows':
# asyncfile.Popen must be used instead of subprocess.Popen
pipe = asyncoro.asyncfile.Popen([r'\cygwin64\bin\sha1sum.exe'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
else:
pipe = subprocess.Popen(['sha1sum'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
async_pipe = asyncoro.asyncfile.AsyncPipe(pipe)
reader = asyncoro.Coro(read_proc, async_pipe)
writer = asyncoro.Coro(write_proc, open(input), async_pipe)
stdout = yield reader.finish()
print(' feeder sha1sum: %s' % stdout)
# asyncoro.logger.setLevel(asyncoro.Logger.DEBUG)
# simpler version using 'communicate'
def communicate(input, coro=None):
if platform.system() == 'Windows':
# asyncfile.Popen must be used instead of subprocess.Popen
pipe = asyncoro.asyncfile.Popen([r'\cygwin64\bin\sha1sum.exe'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
else:
pipe = subprocess.Popen(['sha1sum'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# convert pipe to asynchronous version
async_pipe = asyncoro.asyncfile.AsyncPipe(pipe)
# 'communicate' takes either the data or file descriptor with data
# (if file is too large to read in full) as input
input = open(input)
stdout, stderr = yield async_pipe.communicate(input)
print('communicate sha1sum: %s' % stdout)
def custom_feeder(input, coro=None):
def write_proc(fin, pipe, coro=None):
while True:
data = yield os.read(fin.fileno(), 8*1024)
if not data:
break
n = yield pipe.write(data, full=True)
assert n == len(data)
fin.close()
pipe.stdin.close()
def read_proc(pipe, coro=None):
# output from sha1sum is small, so read until EOF
data = yield pipe.stdout.read()
pipe.stdout.close()
raise StopIteration(data)
if platform.system() == 'Windows':
# asyncfile.Popen must be used instead of subprocess.Popen
pipe = asyncoro.asyncfile.Popen([r'\cygwin64\bin\sha1sum.exe'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
else:
pipe = subprocess.Popen(['sha1sum'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
async_pipe = asyncoro.asyncfile.AsyncPipe(pipe)
reader = asyncoro.Coro(read_proc, async_pipe)
writer = asyncoro.Coro(write_proc, open(input), async_pipe)
stdout = yield reader.finish()
print(' feeder sha1sum: %s' % stdout)
# asyncoro.logger.setLevel(asyncoro.Logger.DEBUG)
# simpler version using 'communicate'
def terminate(self):
"""Close pipe and terminate child process.
"""
self.close()
super(Popen, self).terminate()
def __init__(self, first, last=None):
"""'first' is a Popen object. 'last', if given, is another
Popen object that is the end of the joints to 'first'.
'write' operations send data to first's stdin and 'read'
operations get data from last's stdout/stderr.
"""
if not last:
last = first
self.first = first
self.last = last
if platform.system() == 'Windows':
if not isinstance(first, Popen) or not isinstance(last, Popen):
raise ValueError('argument must be asyncfile.Popen object')
if first.stdin:
self.stdin = first.stdin
else:
self.stdin = None
if last.stdout:
self.stdout = last.stdout
else:
self.stdout = None
if last.stderr:
self.stderr = last.stderr
else:
self.stderr = None
else:
if not isinstance(first, subprocess.Popen) or not isinstance(last, subprocess.Popen):
raise ValueError('argument must be subprocess.Popen object')
if first.stdin:
self.stdin = AsyncFile(first.stdin)
else:
self.stdin = None
if last.stdout:
self.stdout = AsyncFile(last.stdout)
else:
self.stdout = None
if last.stderr:
self.stderr = AsyncFile(last.stderr)
else:
self.stderr = None
def poll(self):
"""Similar to 'poll' of Popen.
"""
if self.last:
return self.last.poll()
elif self.first:
return self.first.poll()
def custom_feeder(input, coro=None):
def write_proc(fin, pipe, coro=None):
while True:
data = yield os.read(fin.fileno(), 8*1024)
if not data:
break
n = yield pipe.write(data, full=True)
assert n == len(data)
fin.close()
pipe.stdin.close()
def read_proc(pipe, coro=None):
# output from sha1sum is small, so read until EOF
data = yield pipe.stdout.read()
pipe.stdout.close()
raise StopIteration(data)
if platform.system() == 'Windows':
# asyncfile.Popen must be used instead of subprocess.Popen
pipe = asyncoro.asyncfile.Popen([r'\cygwin64\bin\sha1sum.exe'],
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
else:
pipe = subprocess.Popen(['sha1sum'], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
async_pipe = asyncoro.asyncfile.AsyncPipe(pipe)
reader = asyncoro.Coro(read_proc, async_pipe)
writer = asyncoro.Coro(write_proc, open(input), async_pipe)
stdout = yield reader.finish()
print(' feeder sha1sum: %s' % stdout)
# asyncoro.logger.setLevel(asyncoro.Logger.DEBUG)
# simpler version using 'communicate'
def terminate(self):
"""Close pipe and terminate child process.
"""
self.close()
super(Popen, self).terminate()
def __init__(self, first, last=None):
"""'first' is a Popen object. 'last', if given, is another
Popen object that is the end of the joints to 'first'.
'write' operations send data to first's stdin and 'read'
operations get data from last's stdout/stderr.
"""
if not last:
last = first
self.first = first
self.last = last
if platform.system() == 'Windows':
if not isinstance(first, Popen) or not isinstance(last, Popen):
raise ValueError('argument must be asyncfile.Popen object')
if first.stdin:
self.stdin = first.stdin
else:
self.stdin = None
if last.stdout:
self.stdout = last.stdout
else:
self.stdout = None
if last.stderr:
self.stderr = last.stderr
else:
self.stderr = None
else:
if not isinstance(first, subprocess.Popen) or not isinstance(last, subprocess.Popen):
raise ValueError('argument must be subprocess.Popen object')
if first.stdin:
self.stdin = AsyncFile(first.stdin)
else:
self.stdin = None
if last.stdout:
self.stdout = AsyncFile(last.stdout)
else:
self.stdout = None
if last.stderr:
self.stderr = AsyncFile(last.stderr)
else:
self.stderr = None
def poll(self):
"""Similar to 'poll' of Popen.
"""
if self.last:
return self.last.poll()
elif self.first:
return self.first.poll()
def execute(cmd, success_msg="", failure_msg="", exitcode=-1):
"""
Generic wrapper to execute the CLI commands. Returns Output if success.
On success it can print message in stdout if specified.
On failure, exits after writing to stderr.
"""
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode == 0:
if success_msg:
output_ok(success_msg)
return out
else:
err_msg = err if err else out
output_notok(failure_msg, err=err_msg, exitcode=exitcode)
def get_glusterd_workdir():
"""
Command to get Glusterd working dir. If failed returns the
default directory /var/lib/glusterd
"""
p = subprocess.Popen(["gluster", "system::", "getwd"],
stdout=subprocess.PIPE)
out, _ = p.communicate()
if p.returncode == 0:
return out.strip()
else:
return DEFAULT_GLUSTERD_WORKDIR
def parse_tox(self):
proc = subprocess.Popen(
"tox -l", shell=True, stdout=subprocess.PIPE, cwd=self.cwd)
self.tox_lines = proc.stdout.read().strip().split('\n')
self.parse_python_versions()