本文整理汇总了Python中os.isatty方法的典型用法代码示例。如果您正苦于以下问题:Python os.isatty方法的具体用法?Python os.isatty怎么用?Python os.isatty使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类os
的用法示例。
在下文中一共展示了os.isatty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _is_daemonized
# 需要导入模块: import os [as 别名]
# 或者: from os import isatty [as 别名]
def _is_daemonized(self):
"""Return boolean indicating if the current process is
running as a daemon.
The criteria to determine the `daemon` condition is to verify
if the current pid is not the same as the one that got used on
the initial construction of the plugin *and* the stdin is not
connected to a terminal.
The sole validation of the tty is not enough when the plugin
is executing inside other process like in a CI tool
(Buildbot, Jenkins).
"""
return (
self._original_pid != os.getpid() and
not os.isatty(sys.stdin.fileno())
)
示例2: getuser
# 需要导入模块: import os [as 别名]
# 或者: from os import isatty [as 别名]
def getuser():
sysuser = os.getenv("USER")
# if sysuser could not be identified try Logname
if sysuser == None:
print("Getuser: Running from crontab -- trying Logname to identify user")
try:
sysuser = os.getenv("LOGNAME").replace("LOGNAME=", "")
except:
sysuser = None
if not sysuser == None:
print("Getuser: ... succes - using", sysuser)
# if sysuser still could not be identified assume that uid 1000 is the defaultuser (on linux)
if sysuser == None or sysuser == 'None':
print("Getuser: Cannot identify user by standard procedures - switching to default uid 1000")
sysuser = pwd.getpwuid(1000)[0]
print("Getuser: now using", sysuser)
return sysuser
# path to home directory
#if os.isatty(sys.stdin.fileno()):
# sysuser = os.getenv("USER")
# pass
#else:
# sysuser = os.getenv("LOGNAME").replace("LOGNAME=", "")
# pass
示例3: disp_recs_json
# 需要导入模块: import os [as 别名]
# 或者: from os import isatty [as 别名]
def disp_recs_json(flt, sort, limit, skip):
if os.isatty(sys.stdout.fileno()):
indent = 4
else:
indent = None
for rec in db.passive.get(flt, sort=sort, limit=limit, skip=skip):
for fld in ['_id', 'scanid']:
try:
del rec[fld]
except KeyError:
pass
if (
rec.get('recontype') == 'SSL_SERVER' and
rec.get('source') in {'cert', 'cacert'}
):
rec['value'] = utils.encode_b64(rec['value']).decode()
print(json.dumps(rec, indent=indent, default=db.passive.serialize))
示例4: size
# 需要导入模块: import os [as 别名]
# 或者: from os import isatty [as 别名]
def size(fileno):
"""Current terminal height and width (lines and columns).
:params int fileno: file-descriptor
:returns: Tuple of two integers - lines and columns respectively.
``(None, None)`` if ``fileno`` is not a terminal
"""
if not isatty(fileno):
return None, None
try:
size = struct.unpack(
'2h', fcntl.ioctl(fileno, termios.TIOCGWINSZ, ' '))
except Exception:
size = (os.getenv('LINES', 25), os.getenv('COLUMNS', 80))
return size
示例5: write
# 需要导入模块: import os [as 别名]
# 或者: from os import isatty [as 别名]
def write(self, text, newline=False):
"""Use ``\\r`` to overdraw the current line with the given text.
This function transparently handles tracking how much overdrawing is
necessary to erase the previous line when used consistently.
:param text: The text to be outputted
:param newline: Whether to start a new line and reset the length count.
:type text: :class:`~__builtins__.str`
:type newline: :class:`~__builtins__.bool`
"""
if not self.isatty:
self.fobj.write('%s\n' % text)
return
msg_len = len(text)
self.max_len = max(self.max_len, msg_len)
self.fobj.write("\r%-*s" % (self.max_len, text))
if newline or not self.isatty:
self.fobj.write('\n')
self.max_len = 0
示例6: size
# 需要导入模块: import os [as 别名]
# 或者: from os import isatty [as 别名]
def size(fd):
"""
Return a tuple (rows,cols) representing the size of the TTY `fd`.
The provided file descriptor should be the stdout stream of the TTY.
If the TTY size cannot be determined, returns None.
"""
if not os.isatty(fd.fileno()):
return None
try:
dims = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, 'hhhh'))
except:
try:
dims = (os.environ['LINES'], os.environ['COLUMNS'])
except:
return None
return dims
示例7: getecho
# 需要导入模块: import os [as 别名]
# 或者: from os import isatty [as 别名]
def getecho(self):
'''This returns the terminal echo mode. This returns True if echo is
on or False if echo is off. Child applications that are expecting you
to enter a password often set ECHO False. See waitnoecho().
Not supported on platforms where ``isatty()`` returns False. '''
try:
attr = termios.tcgetattr(self.fd)
except termios.error as err:
errmsg = 'getecho() may not be called on this platform'
if err.args[0] == errno.EINVAL:
raise IOError(err.args[0], '%s: %s.' % (err.args[1], errmsg))
raise
self.echo = bool(attr[3] & termios.ECHO)
return self.echo
示例8: colorize
# 需要导入模块: import os [as 别名]
# 或者: from os import isatty [as 别名]
def colorize(cmd):
from os import isatty
if isatty(1):
template = '\033[36m>\033[m \033[32m{0}\033[m'
else:
template = '> {0}'
return template.format(shellescape(cmd))
示例9: _check_interactive
# 需要导入模块: import os [as 别名]
# 或者: from os import isatty [as 别名]
def _check_interactive(*descriptors):
for desc in descriptors:
try:
if not isatty(desc.fileno()):
return False
except Exception:
# Anything broken we are going to pretend this is not
# interactive
return False
return True # pragma: no cover
示例10: _column_max_default
# 需要导入模块: import os [as 别名]
# 或者: from os import isatty [as 别名]
def _column_max_default(self):
# 1 == stdout
return -1 if os.isatty(1) else 80
示例11: color_string
# 需要导入模块: import os [as 别名]
# 或者: from os import isatty [as 别名]
def color_string(cls, input_str):
if os.isatty(0):
out = re.sub(r"begin_(\w+)\(", lambda m: cls[m.group(1)].colored_begin(), input_str)
out = re.sub(r"\).end_(\w+)", lambda m: cls[m.group(1)].colored_end(), out)
return out
else:
return input_str
示例12: main
# 需要导入模块: import os [as 别名]
# 或者: from os import isatty [as 别名]
def main():
fd = sys.stdin.fileno()
locale.setlocale(locale.LC_ALL, '')
encoding = locale.getpreferredencoding()
print('os.isatty({0}) => {1}'.format(fd, os.isatty(fd)))
print('locale.getpreferredencoding() => {0}'.format(encoding))
display_conf(kind='pathconf',
names=os.pathconf_names,
getter=lambda name: os.fpathconf(fd, name))
try:
(iflag, oflag, cflag, lflag, ispeed, ospeed, cc
) = termios.tcgetattr(fd)
except termios.error as err:
print('stdin is not a typewriter: {0}'.format(err))
else:
display_bitmask(kind='Input Mode',
bitmap=BITMAP_IFLAG,
value=iflag)
display_bitmask(kind='Output Mode',
bitmap=BITMAP_OFLAG,
value=oflag)
display_bitmask(kind='Control Mode',
bitmap=BITMAP_CFLAG,
value=cflag)
display_bitmask(kind='Local Mode',
bitmap=BITMAP_LFLAG,
value=lflag)
display_ctl_chars(index=CTLCHAR_INDEX,
cc=cc)
print('os.ttyname({0}) => {1}'.format(fd, os.ttyname(fd)))
print('os.ctermid() => {0}'.format(os.ttyname(fd)))
示例13: supports_ansi_escape_codes
# 需要导入模块: import os [as 别名]
# 或者: from os import isatty [as 别名]
def supports_ansi_escape_codes(fd):
"""Returns whether the output device is capable of interpreting ANSI escape
codes when :func:`print_` is used.
Args:
fd (int): file descriptor (e.g. ``sys.stdout.fileno()``)
Returns:
`bool`
"""
if os.isatty(fd):
return True
if not is_win:
return False
# Check for cygwin/msys terminal
handle = winapi._get_osfhandle(fd)
if handle == winapi.INVALID_HANDLE_VALUE:
return False
if winapi.GetFileType(handle) != winapi.FILE_TYPE_PIPE:
return False
file_name = _get_file_name_for_handle(handle)
match = re.match(
"^\\\\(cygwin|msys)-[a-z0-9]+-pty[0-9]+-(from|to)-master$", file_name)
return match is not None
示例14: displayhosts
# 需要导入模块: import os [as 别名]
# 或者: from os import isatty [as 别名]
def displayhosts(recordsgen, out=sys.stdout, **kargs):
"""Displays (on `out`, by default `sys.stdout`) the Nmap scan
results generated by `recordsgen`.
"""
if isinstance(recordsgen, dict):
recordsgen = [recordsgen]
for record in recordsgen:
displayhost(record, out=out, **kargs)
if os.isatty(out.fileno()):
input()
else:
out.write('\n')
示例15: displayfunction_json
# 需要导入模块: import os [as 别名]
# 或者: from os import isatty [as 别名]
def displayfunction_json(cur, dbase, no_screenshots=False):
if os.isatty(sys.stdout.fileno()):
indent = 4
else:
indent = None
for h in cur:
for fld in ['_id', 'scanid']:
try:
del h[fld]
except KeyError:
pass
for port in h.get('ports', []):
if no_screenshots:
for fname in ['screenshot', 'screendata']:
if fname in port:
del port[fname]
elif 'screendata' in port:
port['screendata'] = utils.encode_b64(
dbase.from_binary(port['screendata'])
)
for script in port.get('scripts', []):
if 'masscan' in script and 'raw' in script['masscan']:
script['masscan']['raw'] = utils.encode_b64(
dbase.from_binary(
script['masscan']['raw']
)
)
print(json.dumps(h, indent=indent,
default=dbase.serialize))