本文整理汇总了Python中sys.stdout.fileno函数的典型用法代码示例。如果您正苦于以下问题:Python fileno函数的具体用法?Python fileno怎么用?Python fileno使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了fileno函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: daemonize
def daemonize(self):
"""
Forks the process(es) from the controlling terminal
and redirects I/O streams for logging.
"""
self.fork()
chdir(getcwd())
setsid()
umask(0)
self.fork()
stdout.flush()
stderr.flush()
si= file(self.stdin, 'w+')
so= file(self.stdout, 'a+')
se= file(self.stderr, 'a+', 0)
dup2(si.fileno(), stdin.fileno())
dup2(so.fileno(), stdout.fileno())
dup2(se.fileno(), stderr.fileno())
register(self.del_pid)
self.set_pid()
示例2: parse_args
def parse_args():
p = argparse.ArgumentParser(description='Create a git repository with the history of the specified Wikipedia article.')
p.add_argument('article_name')
p.add_argument('-n', '--no-import', dest='doimport', default=True, action='store_false',
help="Don't invoke git fast-import; only generate fast-import data stream")
p.add_argument('-o', '--out', help='Output directory or fast-import stream file')
g=p.add_mutually_exclusive_group()
g.add_argument('--lang', default=lang, help='Wikipedia language code (default %(default)s)')
g.add_argument('--site', help='Alternate site (e.g. http://commons.wikimedia.org[/w/])')
args = p.parse_args()
if not args.doimport:
if args.out is None:
# http://stackoverflow.com/a/2374507/20789
if platform == "win32":
import os, msvcrt
msvcrt.setmode(stdout.fileno(), os.O_BINARY)
args.out = stdout
else:
try:
args.out = argparse.FileType('wb')(args.out)
except argparse.ArgumentTypeError as e:
p.error(e.args[0])
return p, args
示例3: get_terminal_size_posix
def get_terminal_size_posix():
def ioctl_GWINSZ(fd):
try:
import fcntl
import termios
cr = struct.unpack('hh',
fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234'))
return cr
except:
pass
cr = ioctl_GWINSZ(stdin.fileno()) or \
ioctl_GWINSZ(stdout.fileno()) or \
ioctl_GWINSZ(stderr.fileno())
if not cr:
try:
with os.open(os.ctermid(), os.O_RDONLY) as fd:
cr = ioctl_GWINSZ(fd)
except:
pass
if not cr:
try:
cr = (os.environ['LINES'], os.environ['COLUMNS'])
except:
pass
if not cr:
raise TerminalError('cannot determine terminal size from POSIX')
return int(cr[1]), int(cr[0])
示例4: _daemonize
def _daemonize(self):
try:
pid = os.fork()
if pid > 0:
exit()
except OSError as e:
error(_('Error entering daemon mode: %s') % e.strerror)
exit()
os.chdir('/')
os.setsid()
os.umask(0)
stdout.flush()
stderr.flush()
si = open(os.devnull, 'r')
so = open(os.devnull, 'a+')
se = open(os.devnull, 'a+')
os.dup2(si.fileno(), stdin.fileno())
os.dup2(so.fileno(), stdout.fileno())
os.dup2(se.fileno(), stderr.fileno())
on_exit(self._quit)
old_log = getLogger()
if old_log.handlers:
for handler in old_log.handlers:
old_log.removeHandler(handler)
log(filename=self.logfile, level=self.loglevel,
format='%(asctime)s %(levelname)-8s %(message)s')
self._set_pid()
示例5: darwin_terminal_shell_is_focused
def darwin_terminal_shell_is_focused():
focused_tty = osascript_tell(
'Terminal',
'tty of (first tab of (first window whose frontmost is true) '
'whose selected is true)',
)
return focused_tty == ttyname(stdout.fileno())
示例6: daemonize
def daemonize(self):
try:
pid = fork()
if pid > 0:
# exit first parent
_exit(0)
except OSError as e:
stderr.write(
"fork #1 failed: {0:d} ({1:s})\n".format(
e.errno, str(e)
)
)
raise SystemExit(1)
# decouple from parent environment
chdir(self.path)
setsid()
umask(0)
# do second fork
try:
pid = fork()
if pid > 0:
# exit from second parent
_exit(0)
except OSError as e:
stderr.write(
"fork #2 failed: {0:d} ({1:s})\n".format(
e.errno, str(e)
)
)
raise SystemExit(1)
# redirect standard file descriptors
stdout.flush()
stderr.flush()
maxfd = getrlimit(RLIMIT_NOFILE)[1]
if maxfd == RLIM_INFINITY:
maxfd = 2048
closerange(0, maxfd)
si = open(self.stdin, "r")
so = open(self.stdout, "a+")
se = open(self.stderr, "a+")
dup2(si.fileno(), stdin.fileno())
dup2(so.fileno(), stdout.fileno())
dup2(se.fileno(), stderr.fileno())
self.fire(writepid())
self.fire(daemonized(self))
示例7: read_data
def read_data(cmd_txt, parm, server_addr, fname, skip, get):
res = b""
try:
s = socket()
s.settimeout(5)
s.connect(server_addr)
if s:
# pack & send command
cmd = cmd_txt + parm
cmd = pack("<l%ds" % len(cmd), len(cmd), cmd.encode())
s.send(cmd)
# get length of response
ss = s.recv(4)
size = unpack("<l", ss)[0]
# skip header
hdr_size = len(cmd_txt) + 4
name = s.recv(hdr_size)
# stderr.write("Command %s, parm %s, Size %d, Header_size %d\n" % (cmd_txt, parm, size, hdr_size))
size -= hdr_size
# open file, if required
if fname != None:
if fname:
f = open(fname, "wb")
else:
f = fdopen(stdout.fileno(), 'wb') # binary stdout
# if additional skip, do it
while skip > 0:
img = s.recv(min(skip, 4096))
size -= len(img)
skip -= len(img)
# check, whether not the full data is required
if get > 0 and get < size:
skip = size - get
size = get
# get bulk data
while size > 0:
img = s.recv(min(size, 4096))
if fname != None:
f.write(img)
else:
res += img
size -= len(img)
# eat up what's left
while skip > 0:
img = s.recv(min(skip, 4096))
skip -= len(img)
# and that's it
if fname:
f.close()
s.close()
return res
except Exception as err:
stderr.write("Error attempting to get data, reason: %s\n" % err)
return False
示例8: open_log
def open_log(folder, name, use_stdout=False):
"""Return a writable file-like object representing a log file.
:arg folder: The folder to put the log file in
:arg name: The name of the log file
:arg use_stdout: If True, return a handle to stdout for verbose output,
duplicated so it can be closed with impunity.
"""
if use_stdout:
return fdopen(dup(stdout.fileno()), 'w')
return open(join(folder, name), 'w', 1)
示例9: daemonize
def daemonize(self):
if fork(): exit(0)
umask(0)
setsid()
if fork(): exit(0)
stdout.flush()
stderr.flush()
si = file('/dev/null', 'r')
so = file('/dev/null', 'a+')
se = file('/dev/null', 'a+', 0)
dup2(si.fileno(), stdin.fileno())
dup2(so.fileno(), stdout.fileno())
dup2(se.fileno(), stderr.fileno())
示例10: open_log
def open_log(config_or_tree, name, use_stdout=False):
"""Return a writable file-like object representing a log file.
:arg config_or_tree: a Config or Tree object which tells us which folder to
put the log file in
:arg name: The name of the log file
:arg use_stdout: If True, return a handle to stdout for verbose output,
duplicated so it can be closed with impunity.
"""
if use_stdout:
return os.fdopen(dup(stdout.fileno()), 'w')
return open(os.path.join(config_or_tree.log_folder, name), 'w', 1)
示例11: sudo
def sudo(command):
"""do shell "%s" with administrator privileges
http://developer.apple.com/library/mac/#technotes/tn2065/_index.html"""
if isatty(stdout.fileno()): # terminal
cmd="sudo %s" % command
r=run(cmd)
else: # GUI
escaped=command.replace('"','\\"')
cmd='do shell script "%s" with administrator privileges' % escaped
r=run("osascript",cmd)
if r.status_code==0:
return r.std_out
else:
raise Exception(r.std_err)
示例12: _prompting_input
def _prompting_input(self):
'''
Return prompting stdin.__iter__ decorator...
If either:
- prompt explicitly specified.
- both stdin/out are a tty
'''
if self.args.prompt or \
isatty(stdin.fileno()) and isatty(stdout.fileno()):
return InteractiveInput(prompt=self.args.prompt or
self.DEFAULT_PROMPT)
else:
return stdin
示例13: parse_args
def parse_args():
"""Parses the command line arguments."""
p = argparse.ArgumentParser(
description='Create a git repository with the history of the specified Wikipedia article.')
p.add_argument('article_name')
output = p.add_argument_group('Output options')
g = output.add_mutually_exclusive_group()
g.add_argument('-n', '--no-import', dest='doimport', default=True, action='store_false',
help='Don\'t invoke git fast-import; only generate fast-import data stream')
g.add_argument('-b', '--bare', action='store_true',
help='Import to a bare repository (no working tree)')
output.add_argument('-o', '--out',
help='Output directory or fast-import stream file')
site = p.add_argument_group('MediaWiki site selection')
g = site.add_mutually_exclusive_group()
g.add_argument('--lang', default=locale.getdefaultlocale()[0].split('_')[0] or '',
help='Wikipedia language code (default %(default)s)')
g.add_argument('--site',
help='Alternate MediaWiki site (e.g. https://commons.wikimedia.org[/w/])')
revision = p.add_argument_group('Revision options')
revision.add_argument('--expandtemplates', action='store_true', help='Expand templates')
revision.add_argument('--start', help='ISO8601 timestamp to start listing from')
revision.add_argument('--end', help='ISO8601 timestamp to end listing at')
revision.add_argument('--user', help='Only list revisions made by this user')
revision.add_argument('--excludeuser', help='Exclude revisions made by this user')
args = p.parse_args()
if not args.doimport:
if args.out is None:
# https://stackoverflow.com/a/2374507/20789
if platform == 'win32':
import msvcrt
msvcrt.setmode(stdout.fileno(), os.O_BINARY)
try:
args.out = stdout.buffer
except AttributeError:
args.out = stdout
else:
try:
args.out = argparse.FileType('wb')(args.out)
except argparse.ArgumentTypeError as e:
p.error(e.args[0])
return p, args
示例14: extractlayers
def extractlayers(dc, args, layers, top_most_layer_id):
target_path = args.target
flags = O_WRONLY
if target_path == _TARGET_STDOUT:
target_fd = stdout.fileno()
else:
flags |= O_CREAT | O_TRUNC
if not args.force:
flags |= O_EXCL
target_fd = logexception(_LOGGER, ERROR, 'unable to open target file "{}": {{e}}'.format(target_path), os_open, target_path, flags, 0o666)
with fdopen(target_fd, 'wb') as target_file:
if hasattr(target_file, 'seekable'):
seekable = target_file.seekable()
else:
try:
seekable = not lseek(target_fd, 0, SEEK_CUR) < 0 \
and S_ISREG(fstat(target_fd).st_mode)
except OSError as e:
if errorcode.get(e.errno) != 'ESPIPE':
raise
seekable = False
open_args = { 'fileobj': target_file }
if args.compression is None:
open_args['mode'] = 'w' if seekable else 'w|'
else:
if seekable:
mode = 'w:{}'
open_args['compresslevel'] = args.compress_level
_, ext = ospath_splitext(target_path)
if ext.lower() != '{}{}'.format(ospath_extsep, args.compression):
_LOGGER.warning('target name "%s" doesn\'t match compression type ("%s")', target_path, args.compression)
else:
mode = 'w|{}'
_LOGGER.warning('target "%s" is not seekable, ignoring compression level (%d)', target_path, args.compress_level)
open_args['mode'] = mode.format(args.compression)
with tarfile_open(**open_args) as tar_file:
dimgx_extractlayers(dc, layers, tar_file, top_most_layer_id)
示例15: __init__
def __init__(self, device, baudrate=None, parity=None, rtscts=False,
debug=False):
self._termstates = []
if not mswin and stdout.isatty():
self._termstates = [(fd, tcgetattr(fd)) for fd in
(stdin.fileno(), stdout.fileno(),
stderr.fileno())]
self._device = device
self._baudrate = baudrate or self.DEFAULT_BAUDRATE
self._port = self._open_port(self._device, self._baudrate, parity,
rtscts, debug)
self._resume = False
self._silent = False
self._rxq = deque()
self._rxe = Event()
self._debug = debug
register(self._cleanup)