Here are the examples of the python api sys.stdin.isatty taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
145 Examples
4
Example 1
Project: uncurl Source File: bin.py
def main():
if sys.stdin.isatty():
if len(sys.argv) > 1:
# If an argument is passed
result = parse(sys.argv[1])
else:
# Otherwise pull from clipboard
result = parse(xerox.paste())
else:
result = parse(sys.stdin.read())
print(result)
4
Example 2
Project: prudentia Source File: io.py
def _hidden_input(msg):
first_time_input()
# When using here docuements the getpass does not accept automatic inputs
# so we fall back to the raw input.
# The raw input will not display the information provided through the heredoc
if not sys.stdin.isatty():
return _input(msg)
else:
return getpass(msg)
3
Example 3
Project: meocloud-cli Source File: handler.py
def get_input(self):
if not sys.stdin.isatty():
log.warning('CLI: Must get input but stdin is not a terminal.')
self.out()
self.out('ERROR: Must get input but stdin is not a terminal.')
self.stop(quiet=True)
self.out('Goodbye!')
sys.exit(1)
return input().strip()
3
Example 4
Project: conary Source File: logger.py
def _controlTerminal(self):
try:
# the child should control stdin -- if stdin is a tty
# that can be controlled
if sys.stdin.isatty():
os.tcsetpgrp(0, os.getpgrp())
except AttributeError:
# stdin might not even have an isatty method
pass
3
Example 5
Project: clustershell Source File: Clush.py
def bind_stdin(worker, display):
"""Create a stdin->port->worker binding: connect specified worker
to stdin with the help of a reader thread and a ClusterShell Port
object."""
assert not sys.stdin.isatty()
# Create a ClusterShell Port object bound to worker's task. This object
# is able to receive messages in a thread-safe manner and then will safely
# trigger ev_msg() on a specified event handler.
port = worker.task.port(handler=StdInputHandler(worker), autoclose=True)
# Launch a dedicated thread to read stdin in blocking mode. Indeed stdin
# can be a file, so we cannot use a WorkerSimple here as polling on file
# may result in different behaviors depending on selected engine.
stdin_thread = threading.Thread(None, _stdin_thread_start, args=(port, display))
# setDaemon because we're sometimes left with data that has been read and
# ssh connection already closed.
# Syntax for compat with Python < 2.6
stdin_thread.setDaemon(True)
stdin_thread.start()
3
Example 6
Project: titan Source File: titan_rpc.py
def create_auth_func():
"""Default auth func."""
email = ''
password = ''
if sys.stdin.isatty():
email = raw_input('Email: ')
password = getpass.getpass('Password: ')
return lambda: (email, password)
3
Example 7
def get_stdin():
"""
Grab stdin, printing simple instructions if it's interactive.
"""
if sys.stdin.isatty():
print('Enter a JSON object, then press ctrl-D')
return sys.stdin
3
Example 8
Project: alertlib Source File: alert.py
def main(argv):
parser = setup_parser()
args = parser.parse_args(argv)
if sys.stdin.isatty():
print >>sys.stderr, '>> Enter the message to alert, then hit control-D'
message = sys.stdin.read().strip()
if args.dry_run:
alertlib.enter_test_mode()
logging.getLogger().setLevel(logging.INFO)
alert(message, args)
3
Example 9
Project: ansible Source File: vault.py
def execute_decrypt(self):
if len(self.args) == 0 and sys.stdin.isatty():
display.display("Reading ciphertext input from stdin", stderr=True)
for f in self.args or ['-']:
self.editor.decrypt_file(f, output_file=self.options.output_file)
if sys.stdout.isatty():
display.display("Decryption successful", stderr=True)
3
Example 10
Project: python-glanceclient Source File: shell.py
def _is_image_data_provided(args):
"""Return True if some image data has probably been provided by the user"""
# NOTE(kragniz): Check stdin works, then check is there is any data
# on stdin or a filename has been provided with --file
try:
os.fstat(0)
except OSError:
return False
return not sys.stdin.isatty() or args.file or args.copy_from
3
Example 11
def get_stdin():
"""
Get data from stdin, if any
"""
if not sys.stdin.isatty():
for line in sys.stdin:
yield line
return
3
Example 12
Project: mycli Source File: main.py
def confirm_destructive_query(queries):
"""Check if the query is destructive and prompts the user to confirm.
Returns:
None if the query is non-destructive or we can't prompt the user.
True if the query is destructive and the user wants to proceed.
False if the query is destructive and the user doesn't want to proceed.
"""
prompt_text = ("You're about to run a destructive command.\n"
"Do you want to proceed? (y/n)")
if is_destructive(queries) and sys.stdin.isatty():
return click.prompt(prompt_text, type=bool)
3
Example 13
def parse_args(self, argv):
"""Parse the given CLI arguments into a namespace object.
Args:
argv (list): List of CLI arguments, not including argv0
Returns:
argparse.Namespace: Parser namespace object
"""
# Parse the user input
args = self.parser.parse_args(argv)
# If being run non-interactively, treat as if --force is set, in order
# to avoid hanging while trying to read input that will never come.
if not (sys.stdin.isatty() and sys.stdout.isatty()):
args._force = True # pylint: disable=protected-access
return args
3
Example 14
def getch(str="Press any key to continue"):
"configurable pause of execution"
import sys, subprocess
if sys.stdin.isatty():
if str is not None:
print str
if sys.platform[:3] != 'win':
raw,cooked = 'stty raw','stty cooked'
else:
raw,cooked = '',''
subprocess.call(raw, shell=True)
a = sys.stdin.read(1)
subprocess.call(cooked, shell=True)
return a
else:
if str is not None:
print str + " and press enter"
return raw_input()
3
Example 15
@staticmethod
def valid(string):
'''Check if we allow the opening of stdin'''
if string is None and sys.stdin.isatty():
raise IOError('no input specified but terminal is interactive')
return True
3
Example 16
Project: pyfs Source File: scriptsupport.py
def run_for_input(what, args):
if not sys.stdin.isatty():
stdin_idx = args.index("-") if "-" in args else None
for line in get_line_from_stdin():
element = decode_input(line)
funcargs = decode_strings(args)
if stdin_idx is not None:
funcargs[stdin_idx:stdin_idx+1] = [element]
else:
funcargs[0:0] = [element]
return run_with(what, funcargs)
else:
return run_with(what, decode_strings(args))
3
Example 17
Project: docker-lamp Source File: lamp.py
def run_php(self, user: str, args: str):
self.check_vms_are_running()
tty = 't' if sys.stdin.isatty() else ''
cmd = ['docker', 'exec', '-u', user, '-i' + tty, self.get_vm_item('php', 'name'), 'bash', '-c', '--']
cmd += ['cd /var/' + self.current_dir_relative + '; exec /usr/bin/php ' + args]
subprocess.call(cmd, stdin=sys.stdin)
3
Example 18
def prompt_password(prompt, confirm=True):
import getpass
if sys.stdin.isatty():
password = getpass.getpass(prompt)
if password and confirm:
password2 = getpass.getpass("Confirm: ")
if password != password2:
sys.exit("Error: Passwords do not match.")
else:
password = raw_input(prompt)
if not password:
password = None
return password
3
Example 19
Project: ansible Source File: vault.py
def execute_encrypt(self):
if len(self.args) == 0 and sys.stdin.isatty():
display.display("Reading plaintext input from stdin", stderr=True)
for f in self.args or ['-']:
self.editor.encrypt_file(f, output_file=self.options.output_file)
if sys.stdout.isatty():
display.display("Encryption successful", stderr=True)
3
Example 20
Project: twtxt Source File: helper.py
def validate_text(ctx, param, value):
conf = click.get_current_context().obj["conf"]
if isinstance(value, tuple):
value = " ".join(value)
if not value and not sys.stdin.isatty():
value = click.get_text_stream("stdin").read()
if value:
value = value.strip()
if conf.character_warning and len(value) > conf.character_warning:
click.confirm("✂ Warning: Tweet is longer than {0} characters. Are you sure?".format(
conf.character_warning), abort=True)
return value
else:
raise click.BadArgumentUsage("Text can’t be empty.")
3
Example 21
Project: jaide Source File: cli.py
def run():
if os.name == 'posix' and sys.stdin.isatty():
# set max_content_width to the width of the terminal dynamically
rows, columns = popen('stty size', 'r').read().split()
# obj and max_column_width get passed into click, and don't actually
# proceed into the main() command group. Click handles the CLI
# user options and passing them into main().
main(obj={}, max_content_width=int(columns))
else:
main(obj={})
3
Example 22
Project: udiskie Source File: prompt.py
def password(password_command):
"""
Create a password prompt function.
:param bool hint_gui: whether a GUI input dialog should be preferred
"""
gui = lambda: has_Gtk() and get_password_gui
tty = lambda: sys.stdin.isatty() and get_password_tty
if password_command == 'builtin:gui':
return gui() or tty()
elif password_command == 'builtin:tty':
return tty() or gui()
elif password_command:
return DeviceCommand(password_command)
else:
return None
3
Example 23
def stop(self):
"""Erase the spinner from the screen"""
if sys.stdin.isatty() and not self.nospinner:
sys.stdout.write("\r" + self.message + " ")
sys.stdout.write("\r" + self.message)
sys.stdout.flush()
3
Example 24
Project: pyjip Source File: __init__.py
def read_ids_from_pipe():
"""Read job ids from a stream"""
import sys
job_ids = []
if not sys.stdin.isatty():
for line in sys.stdin:
job_ids.append(line.strip().split("\t")[0])
# reopen stdin
sys.stdin = open('/dev/tty', 'r')
return job_ids
3
Example 25
Project: dcos-cli Source File: main.py
@staticmethod
def _assert_no_tty(command_example):
if sys.stdin.isatty():
# We don't support TTY right now.
# In the future we will start an editor
template = ("We currently don't support reading from the TTY. "
"Please specify an application JSON.\n{}")
raise DCOSException(template.format(command_example))
3
Example 26
Project: GoogleSpeech Source File: __init__.py
def __next__(self):
""" Get a speech segment, splitting text by taking into account spaces, punctuation, and maximum segment size. """
if self.text == "-":
if sys.stdin.isatty():
logging.getLogger().error("Stdin is not a pipe")
return
while True:
new_line = sys.stdin.readline()
if not new_line:
return
segments = __class__.splitText(new_line)
for segment_num, segment in enumerate(segments):
yield SpeechSegment(segment, self.lang, segment_num, len(segments))
else:
segments = __class__.splitText(self.text)
for segment_num, segment in enumerate(segments):
yield SpeechSegment(segment, self.lang, segment_num, len(segments))
3
Example 27
def prompt_password(self, label, confirm=True):
"""
Prompt user for a password or read it in via stdin depending
on whether there is a tty or not.
"""
if sys.stdin.isatty():
prompt = u'%s: ' % unicode(label)
repeat_prompt = unicode(_('Enter %(label)s again to verify: ') % dict(label=label))
while True:
pw1 = self.prompt_helper(prompt, label, prompt_func=getpass.getpass)
if not confirm:
return pw1
pw2 = self.prompt_helper(repeat_prompt, label, prompt_func=getpass.getpass)
if pw1 == pw2:
return pw1
self.print_error( _('Passwords do not match!'))
else:
return self.decode(sys.stdin.readline().strip())
3
Example 28
Project: gup Source File: cmd.py
def _mark_contents(opts, targets):
parent_target = _assert_parent_target('--contents')
if len(targets) == 0:
assert not sys.stdin.isatty()
checksum = Checksum.from_stream(sys.stdin.buffer if PY3 else sys.stdin)
else:
checksum = Checksum.from_files(targets)
TargetState(parent_target).add_dependency(checksum)
3
Example 29
Project: grr Source File: repacking.py
def GetSigningPassword(self):
if sys.stdin.isatty():
print "Enter passphrase for code signing:"
return getpass.getpass()
else:
passwd = sys.stdin.readline().strip()
if not passwd:
raise RuntimeError("Expected signing password on stdin, got nothing.")
return passwd
3
Example 30
Project: crmsh Source File: utils.py
def can_ask():
"""
Is user-interactivity possible?
Checks if connected to a TTY.
"""
return (not options.ask_no) and sys.stdin.isatty()
3
Example 31
def get_user_password(verify, message=None, force_save=False):
if sys.stdin.isatty():
pw = get_tty_password(verify, message, force_save)
else:
pw = get_tk_password(verify, message, force_save)
return pw
3
Example 32
def getoptionvalue(val, prompt):
if not val:
if sys.stdin.isatty():
val = raw_input(prompt)
else:
val = sys.stdin.readline()
if val[-1] == '\n': val = val[:-1]
return val
3
Example 33
def run_from_args(args):
pass_prefix = "#"
if args.aFile == None:
if sys.stdin.isatty():
sys.stderr.write('Please stream in input to this command or specify the file to read\n')
sys.exit(1)
else:
args.aFile = sys.stdin
try:
varLookup(args.aFile, args.bFile, args.output, args.max_distance, pass_prefix, args.cohort_name)
except IOError as err:
sys.stderr.write("IOError " + str(err) + "\n");
3
Example 34
def spin(self):
"""Rotate the spinner"""
if sys.stdin.isatty() and not self.nospinner:
sys.stdout.write("\r" + self.message + " " + self.glyphs[self.pos])
sys.stdout.flush()
self.pos = (self.pos+1) % len(self.glyphs)
3
Example 35
def console(self, vm: str, user: str):
self.check_vms_are_running()
vm_name = self.get_vm_item(vm, 'name')
if vm_name == '':
raise Exception('{} does not seem to be in your services or has crashed'.format(vm))
tty = 't' if sys.stdin.isatty() else ''
subprocess.call(['docker', 'exec', '-u', user, '-i' + tty, vm_name, 'env', 'TERM=xterm', 'bash'])
3
Example 36
Project: python-executor Source File: tests.py
def test_tty_option(self):
"""Make sure the ``tty`` option works as expected."""
# By default we expect the external command to inherit our standard
# input stream (of course this test suite is expected to work
# regardless of whether it's connected to a terminal).
test_stdin_isatty = python_golf('import sys; sys.exit(0 if sys.stdin.isatty() else 1)')
assert sys.stdin.isatty() == execute(*test_stdin_isatty, check=False)
# If the command's output is being captured then its standard
# input stream should be redirected to /dev/null.
self.assertRaises(ExternalCommandFailed, execute, *test_stdin_isatty, capture=True)
# If the caller explicitly disabled interactive terminal support then
# the command's standard input stream should also be redirected to
# /dev/null.
self.assertRaises(ExternalCommandFailed, execute, *test_stdin_isatty, tty=False)
3
Example 37
Project: docker-lamp Source File: lamp.py
def run_mysql(self, args: str):
self.check_vms_are_running()
vm_name = self.get_vm_item('mysql', 'name')
if vm_name == '':
raise Exception('mysql does not seem to be in your services or has crashed')
tty = 't' if sys.stdin.isatty() else ''
password = self.user_config_main.get(
'mysql.root_password',
self.default_config_main.get('mysql.root_password')
)
cmd = ['docker', 'exec', '-u', 'root', '-i' + tty, vm_name]
cmd += ['mysql', '-u', 'root', '-p' + password, args]
subprocess.call(cmd, stdin=sys.stdin)
3
Example 38
Project: conary Source File: epdb_server.py
def _serve_process(self, slaveFd, serverPid):
"""
Serves a process by connecting its outputs/inputs to the pty
slaveFd. serverPid is the process controlling the master fd
that passes that output over the socket.
"""
self.serverPid = serverPid
if sys.stdin.isatty():
self.oldTermios = termios.tcgetattr(sys.stdin.fileno())
else:
self.oldTermios = None
self.oldStderr = os.dup(sys.stderr.fileno())
self.oldStdout = os.dup(sys.stdout.fileno())
self.oldStdin = os.dup(sys.stdin.fileno())
os.dup2(slaveFd, 0)
os.dup2(slaveFd, 1)
os.dup2(slaveFd, 2)
os.close(slaveFd)
self.closed = False
3
Example 39
@command('debug', _('suspend and open debug console'), PERM_SYSADMIN)
def do_debug(self, arg):
if sys.stdin.isatty():
import builtins
from cli import repl
from pyxmpp2.jid import JID
old_ = builtins._
g = locals()
del g['repl'], g['builtins'], g['old_'], g['arg']
repl(g, 'cmd.txt')
builtins._ = old_
else:
self.reply(_('Error: stdin is not terminal.'))
return True
3
Example 40
Project: ete Source File: common.py
def src_tree_iterator(args):
if not args.src_trees and not sys.stdin.isatty():
log.debug("Reading trees from standard input...")
args.src_trees = sys.stdin
if args.src_trees:
for stree in args.src_trees:
yield stree.strip()
elif args.src_tree_list:
for line in open(args.src_tree_list):
line = line.strip()
if line:
yield line
3
Example 41
def mainloop(self):
""" The main loop.
"""
# Print usage if not enough args or bad options
if len(self.args) < 2:
self.parser.error("No event type and info hash given!")
if sys.stdin.isatty():
self.options.no_fork = True
3
Example 42
def setup(self):
self.height, self.width = self.get_tty_size()
self.in_is_tty = sys.stdin.isatty()
self.out_is_tty = sys.stdout.isatty()
self.pretty = self.out_is_tty
if sys.platform == 'win32' and os.getenv('TERM') == 'xterm':
self.pretty = True
3
Example 43
Project: ete Source File: ete.py
def tree_iterator(args):
if not args.src_trees and not sys.stdin.isatty():
log.debug("Reading trees from standard input...")
args.src_trees = sys.stdin
elif not args.src_trees:
log.error("At least one tree is required as input (i.e --src_trees ) ")
sys.exit(-1)
for stree in args.src_trees:
# CHECK WHAT is needed before process the main command, allows mods before analyses
yield stree.strip()
2
Example 44
Project: s3ql Source File: common.py
def get_backend_factory(storage_url, backend_options, authfile,
compress=('lzma', 2), raw=False):
'''Return factory producing backend objects for given storage-url
If *raw* is true, don't attempt to unlock and don't wrap into
ComprencBackend.
'''
from .backends import prefix_map
from .backends.common import (CorruptedObjectError, NoSuchObject, AuthenticationError,
DanglingStorageURLError, AuthorizationError)
from .backends.comprenc import ComprencBackend
hit = re.match(r'^([a-zA-Z0-9]+)://', storage_url)
if not hit:
raise QuietError('Unable to parse storage url "%s"' % storage_url,
exitcode=2)
backend = hit.group(1)
try:
backend_class = prefix_map[backend]
except KeyError:
raise QuietError('No such backend: %s' % backend, exitcode=11)
# Validate backend options
for opt in backend_options.keys():
if opt not in backend_class.known_options:
raise QuietError('Unknown backend option: %s' % opt,
exitcode=3)
# Read authfile
config = configparser.ConfigParser()
if os.path.isfile(authfile):
mode = os.stat(authfile).st_mode
if mode & (stat.S_IRGRP | stat.S_IROTH):
raise QuietError("%s has insecure permissions, aborting." % authfile,
exitcode=12)
config.read(authfile)
backend_login = None
backend_passphrase = None
fs_passphrase = None
for section in config.sections():
def getopt(name):
try:
return config.get(section, name)
except configparser.NoOptionError:
return None
pattern = getopt('storage-url')
if not pattern or not storage_url.startswith(pattern):
continue
backend_login = getopt('backend-login') or backend_login
backend_passphrase = getopt('backend-password') or backend_passphrase
fs_passphrase = getopt('fs-passphrase') or fs_passphrase
if not backend_login and backend_class.needs_login:
if sys.stdin.isatty():
backend_login = getpass("Enter backend login: ")
else:
backend_login = sys.stdin.readline().rstrip()
if not backend_passphrase and backend_class.needs_login:
if sys.stdin.isatty():
backend_passphrase = getpass("Enter backend passphrase: ")
else:
backend_passphrase = sys.stdin.readline().rstrip()
backend = None
try:
backend = backend_class(storage_url, backend_login, backend_passphrase,
backend_options)
# Do not use backend.lookup(), this would use a HEAD request and
# not provide any useful error messages if something goes wrong
# (e.g. wrong credentials)
backend.fetch('s3ql_passphrase')
except AuthenticationError:
raise QuietError('Invalid credentials (or skewed system clock?).',
exitcode=14)
except AuthorizationError:
raise QuietError('No permission to access backend.',
exitcode=15)
except HostnameNotResolvable:
raise QuietError("Can't connect to backend: unable to resolve hostname",
exitcode=19)
except DanglingStorageURLError as exc:
raise QuietError(str(exc), exitcode=16)
except NoSuchObject:
encrypted = False
else:
encrypted = True
finally:
if backend is not None:
backend.close()
if raw:
return lambda: backend_class(storage_url, backend_login, backend_passphrase,
backend_options)
if encrypted and not fs_passphrase:
if sys.stdin.isatty():
fs_passphrase = getpass("Enter file system encryption passphrase: ")
else:
fs_passphrase = sys.stdin.readline().rstrip()
elif not encrypted:
fs_passphrase = None
if fs_passphrase is not None:
fs_passphrase = fs_passphrase.encode('utf-8')
if not encrypted:
return lambda: ComprencBackend(None, compress,
backend_class(storage_url, backend_login,
backend_passphrase, backend_options))
with ComprencBackend(fs_passphrase, compress, backend) as tmp_backend:
try:
data_pw = tmp_backend['s3ql_passphrase']
except CorruptedObjectError:
raise QuietError('Wrong file system passphrase', exitcode=17)
# To support upgrade, temporarily store the backend
# passphrase in every backend object.
def factory():
b = ComprencBackend(data_pw, compress,
backend_class(storage_url, backend_login,
backend_passphrase, backend_options))
b.fs_passphrase = fs_passphrase
return b
return factory
2
Example 45
Project: free_tls_certificates Source File: driver.py
def stop_if_certificate_valid(opts):
# Stop if the certificate is already valid for all of the domains.
import idna
if not os.path.exists(opts["certificate_fn"]):
if sys.stdin.isatty():
sys.stderr.write("Certificate file %s not present...\n" % opts["certificate_fn"])
return
def idna_encode(domain):
# squash exceptions here
try:
return idna.encode(domain).decode("ascii")
except:
return domain
# Load the certificate.
from free_tls_certificates.utils import load_certificate, get_certificate_domains
cert = load_certificate(opts["certificate_fn"])
# If this is a self-signed certificate (and the user is seeking
# a real one), provision a new one.
if cert.issuer == cert.subject and not opts["self_signed"]:
if sys.stdin.isatty():
sys.stderr.write("Replacing self-signed certificate...\n")
return
# If this is expiring within 30 days, provision a new one.
expires_in = cert.not_valid_after - datetime.datetime.now()
if expires_in < datetime.timedelta(days=30):
if sys.stdin.isatty():
sys.stderr.write("Replacing expiring certificate (expires in %s)...\n" % str(expires_in))
return
# If the certificate is not valid for one of the domains we're requesting,
# provision a new one.
request_domains = set(idna_encode(domain) for domain in opts["domains"])
cert_domains = set(get_certificate_domains(cert))
if len(request_domains - cert_domains) > 0:
if sys.stdin.isatty():
sys.stderr.write("Certificate is not valid for %s (found %s)...\n" % (
", ".join(request_domains - cert_domains),
", ".join(cert_domains)
))
return
# Certificate is valid for the requested domains - no need to provision.
if sys.stdout.isatty():
print("Certificate is already valid and good for at least 30 days.")
sys.exit(3)
0
Example 46
Project: fe Source File: clientparameters.py
def resolve_password(
parameters : "a fully normalized set of client parameters(dict)",
getpass = getpass,
prompt_title = '',
):
"""
Given a parameters dictionary, resolve the 'password' key.
If `prompt_password` is `True`.
If sys.stdin is a TTY, use `getpass` to prompt the user.
Otherwise, read a single line from sys.stdin.
delete 'prompt_password' from the dictionary.
Otherwise.
If the 'password' key is `None`, attempt to resolve the password using the
'pgpassfile' key.
Finally, remove the pgpassfile key as the password has been resolved for the
given parameters.
"""
prompt_for_password = parameters.pop('prompt_password', False)
pgpassfile = parameters.pop('pgpassfile', None)
prompt_title = parameters.pop('prompt_title', None)
if prompt_for_password is True:
# it's a prompt
if sys.stdin.isatty():
prompt = prompt_title or parameters.pop('prompt_title', '')
prompt += '[' + pg_iri.serialize(parameters, obscure_password = True) + ']'
parameters['password'] = getpass("Password for " + prompt +": ")
else:
# getpass will throw an exception if it's not a tty,
# so just take the next line.
pw = sys.stdin.readline()
# try to clean it up..
if pw.endswith(os.linesep):
pw = pw[:len(pw)-len(os.linesep)]
parameters['password'] = pw
else:
if parameters.get('password') is None:
# No password? Look in the pgpassfile.
if pgpassfile is not None:
parameters['password'] = pg_pass.lookup_pgpass(parameters, pgpassfile)
0
Example 47
Project: qtop Source File: utils.py
def init_logging(options):
if not options.verbose:
log_level = logging.WARN
elif options.verbose == 1:
log_level = logging.INFO
elif options.verbose >= 2:
log_level = logging.DEBUG
fileutils.mkdir_p(QTOP_LOGFILE.rsplit('/', 1)[0]) # logfile path
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
if options.verbose >= 3:
# this prepends date/time
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s', "%Y-%m-%d %H:%M:%S")
else:
formatter = logging.Formatter('%(levelname)s - %(message)s')
fh = logging.FileHandler(QTOP_LOGFILE)
fh.setLevel(log_level)
fh.setFormatter(formatter)
logger.addHandler(fh)
fh = logging.StreamHandler()
fh.setLevel(logging.ERROR)
fh.setFormatter(formatter)
logger.addHandler(fh)
logger.disabled = False # TODO: maybe make this a cmdline switch? -D ?
logging.info("\n" + "=" * 50 + "STARTING NEW LOG ENTRY..." + "=" * 50 + "\n\n")
logging.debug('Verbosity level = %s' % options.verbose)
logging.debug("input, output isatty: %s\t%s" % (sys.stdin.isatty(), sys.stdout.isatty()))
0
Example 48
Project: rbtools Source File: __init__.py
def credentials_prompt(self, realm, uri, username=None, password=None,
*args, **kwargs):
"""Prompt the user for credentials using the command line.
This will prompt the user, and then return the provided
username and password. This is used as a callback in the
API when the user requires authorization.
"""
if username is None or password is None:
if getattr(self.options, 'diff_filename', None) == '-':
die('HTTP authentication is required, but cannot be '
'used with --diff-filename=-')
# Interactive prompts don't work correctly when input doesn't come
# from a terminal. This could seem to be a rare case not worth
# worrying about, but this is what happens when using native
# Python in Cygwin terminal emulator under Windows and it's very
# puzzling to the users, especially because stderr is also _not_
# flushed automatically in this case, so the program just appears
# to hang.
if not sys.stdin.isatty():
logging.error('Authentication is required but input is not a '
'tty.')
if sys.platform == 'win32':
logging.info('Check that you are not running this script '
'from a Cygwin terminal emulator (or use '
'Cygwin Python to run it).')
raise CommandError('Unable to log in to Review Board.')
print()
print('Please log in to the Review Board server at %s.' %
urlparse(uri)[1])
# getpass will write its prompt to stderr but input
# writes to stdout. See bug 2831.
if username is None:
sys.stderr.write('Username: ')
username = input()
if password is None:
password = getpass.getpass(b'Password: ')
return username, password
0
Example 49
Project: tappy Source File: main.py
def parse_args(argv):
description = _('A TAP consumer for Python')
epilog = _(
'When no files are given or a dash (-) is used for the file name, '
'tappy will read a TAP stream from STDIN.')
parser = argparse.ArgumentParser(description=description, epilog=epilog)
parser.add_argument(
'files', metavar='FILE', nargs='*', help=_(
'A file containing TAP output. Any directories listed will be '
'scanned for files to include as TAP files.'))
parser.add_argument(
'-v', '--verbose', action='store_const', default=1, const=2,
help=_('use verbose messages'))
# argparse expects the executable to be removed from argv.
args = parser.parse_args(argv[1:])
# When no files are provided, the user wants to use a TAP stream on STDIN.
# But they probably didn't mean it if there is no pipe connected.
# In that case, print the help and exit.
if not args.files and sys.stdin.isatty():
sys.exit(parser.print_help())
return args
0
Example 50
Project: baxter_examples Source File: getch.py
def getch(timeout=0.01):
"""
Retrieves a character from stdin.
Returns None if no character is available within the timeout.
Blocks if timeout < 0.
"""
# If this is being piped to, ignore non-blocking functionality
if not sys.stdin.isatty():
return sys.stdin.read(1)
fileno = sys.stdin.fileno()
old_settings = termios.tcgetattr(fileno)
ch = None
try:
tty.setraw(fileno)
rlist = [fileno]
if timeout >= 0:
[rlist, _, _] = select(rlist, [], [], timeout)
if fileno in rlist:
ch = sys.stdin.read(1)
except Exception as ex:
print "getch", ex
raise OSError
finally:
termios.tcsetattr(fileno, termios.TCSADRAIN, old_settings)
return ch