本文整理汇总了Python中IPython.utils.py3compat.PY3属性的典型用法代码示例。如果您正苦于以下问题:Python py3compat.PY3属性的具体用法?Python py3compat.PY3怎么用?Python py3compat.PY3使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类IPython.utils.py3compat
的用法示例。
在下文中一共展示了py3compat.PY3属性的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_UnicodeStdStream
# 需要导入模块: from IPython.utils import py3compat [as 别名]
# 或者: from IPython.utils.py3compat import PY3 [as 别名]
def test_UnicodeStdStream():
# Test wrapping a bytes-level stdout
if PY3:
stdoutb = stdlib_io.BytesIO()
stdout = stdlib_io.TextIOWrapper(stdoutb, encoding='ascii')
else:
stdout = stdoutb = stdlib_io.BytesIO()
orig_stdout = sys.stdout
sys.stdout = stdout
try:
sample = u"@łe¶ŧ←"
unicode_std_stream().write(sample)
output = stdoutb.getvalue().decode('utf-8')
nt.assert_equal(output, sample)
assert not stdout.closed
finally:
sys.stdout = orig_stdout
示例2: error
# 需要导入模块: from IPython.utils import py3compat [as 别名]
# 或者: from IPython.utils.py3compat import PY3 [as 别名]
def error(self, obj, value):
kind = type(value)
if (not py3compat.PY3) and kind is InstanceType:
msg = 'class %s' % value.__class__.__name__
else:
msg = '%s (i.e. %s)' % ( str( kind )[1:-1], repr( value ) )
if obj is not None:
e = "The '%s' trait of %s instance must be %s, but a value of %s was specified." \
% (self.name, class_of(obj),
self.info(), msg)
else:
e = "The '%s' trait must be %s, but a value of %r was specified." \
% (self.name, self.info(), msg)
raise TraitError(e)
示例3: test_raw_input
# 需要导入模块: from IPython.utils import py3compat [as 别名]
# 或者: from IPython.utils.py3compat import PY3 [as 别名]
def test_raw_input():
"""test [raw_]input"""
with new_kernel() as kc:
iopub = kc.iopub_channel
input_f = "input" if py3compat.PY3 else "raw_input"
theprompt = "prompt> "
code = 'print({input_f}("{theprompt}"))'.format(**locals())
msg_id = kc.execute(code, allow_stdin=True)
msg = kc.get_stdin_msg(block=True, timeout=TIMEOUT)
nt.assert_equal(msg['header']['msg_type'], u'input_request')
content = msg['content']
nt.assert_equal(content['prompt'], theprompt)
text = "some text"
kc.input(text)
reply = kc.get_shell_msg(block=True, timeout=TIMEOUT)
nt.assert_equal(reply['content']['status'], 'ok')
stdout, stderr = assemble_output(iopub)
nt.assert_equal(stdout, text + "\n")
示例4: test_eval_input
# 需要导入模块: from IPython.utils import py3compat [as 别名]
# 或者: from IPython.utils.py3compat import PY3 [as 别名]
def test_eval_input():
"""test input() on Python 2"""
with new_kernel() as kc:
iopub = kc.iopub_channel
input_f = "input" if py3compat.PY3 else "raw_input"
theprompt = "prompt> "
code = 'print(input("{theprompt}"))'.format(**locals())
msg_id = kc.execute(code, allow_stdin=True)
msg = kc.get_stdin_msg(block=True, timeout=TIMEOUT)
nt.assert_equal(msg['header']['msg_type'], u'input_request')
content = msg['content']
nt.assert_equal(content['prompt'], theprompt)
kc.input("1+1")
reply = kc.get_shell_msg(block=True, timeout=TIMEOUT)
nt.assert_equal(reply['content']['status'], 'ok')
stdout, stderr = assemble_output(iopub)
nt.assert_equal(stdout, "2\n")
示例5: _inject_cookie_message
# 需要导入模块: from IPython.utils import py3compat [as 别名]
# 或者: from IPython.utils.py3compat import PY3 [as 别名]
def _inject_cookie_message(self, msg):
"""Inject the first message, which is the document cookie,
for authentication."""
if not PY3 and isinstance(msg, unicode):
# Cookie constructor doesn't accept unicode strings
# under Python 2.x for some reason
msg = msg.encode('utf8', 'replace')
try:
identity, msg = msg.split(':', 1)
self.session.session = cast_unicode(identity, 'ascii')
except Exception:
logging.error("First ws message didn't have the form 'identity:[cookie]' - %r", msg)
try:
self.request._cookies = Cookie.SimpleCookie(msg)
except:
self.log.warn("couldn't parse cookie string: %s",msg, exc_info=True)
示例6: read
# 需要导入模块: from IPython.utils import py3compat [as 别名]
# 或者: from IPython.utils.py3compat import PY3 [as 别名]
def read(self, fp, **kwargs):
"""Read a notebook from a file like object"""
nbs = fp.read()
if not py3compat.PY3 and not isinstance(nbs, unicode):
nbs = py3compat.str_to_unicode(nbs)
return self.reads(nbs, **kwargs)
示例7: write
# 需要导入模块: from IPython.utils import py3compat [as 别名]
# 或者: from IPython.utils.py3compat import PY3 [as 别名]
def write(self, nb, fp, **kwargs):
"""Write a notebook to a file like object"""
nbs = self.writes(nb,**kwargs)
if not py3compat.PY3 and not isinstance(nbs, unicode):
# this branch is likely only taken for JSON on Python 2
nbs = py3compat.str_to_unicode(nbs)
return fp.write(nbs)
示例8: test_cast_small
# 需要导入模块: from IPython.utils import py3compat [as 别名]
# 或者: from IPython.utils.py3compat import PY3 [as 别名]
def test_cast_small(self):
"""Integer casts small longs to int"""
if py3compat.PY3:
raise SkipTest("not relevant on py3")
self.obj.value = 100L
self.assertEqual(type(self.obj.value), int)
示例9: test_raw_input
# 需要导入模块: from IPython.utils import py3compat [as 别名]
# 或者: from IPython.utils.py3compat import PY3 [as 别名]
def test_raw_input(self):
""" Does the in-process kernel handle raw_input correctly?
"""
io = StringIO('foobar\n')
sys_stdin = sys.stdin
sys.stdin = io
try:
if py3compat.PY3:
self.kc.execute('x = input()')
else:
self.kc.execute('x = raw_input()')
finally:
sys.stdin = sys_stdin
self.assertEqual(self.km.kernel.shell.user_ns.get('x'), 'foobar')
示例10: test_info
# 需要导入模块: from IPython.utils import py3compat [as 别名]
# 或者: from IPython.utils.py3compat import PY3 [as 别名]
def test_info():
"Check that Inspector.info fills out various fields as expected."
i = inspector.info(Call, oname='Call')
nt.assert_equal(i['type_name'], 'type')
expted_class = str(type(type)) # <class 'type'> (Python 3) or <type 'type'>
nt.assert_equal(i['base_class'], expted_class)
nt.assert_equal(i['string_form'], "<class 'IPython.core.tests.test_oinspect.Call'>")
fname = __file__
if fname.endswith(".pyc"):
fname = fname[:-1]
# case-insensitive comparison needed on some filesystems
# e.g. Windows:
nt.assert_equal(i['file'].lower(), fname.lower())
nt.assert_equal(i['definition'], 'Call(self, *a, **kw)\n')
nt.assert_equal(i['docstring'], Call.__doc__)
nt.assert_equal(i['source'], None)
nt.assert_true(i['isclass'])
nt.assert_equal(i['init_definition'], "Call(self, x, y=1)\n")
nt.assert_equal(i['init_docstring'], Call.__init__.__doc__)
i = inspector.info(Call, detail_level=1)
nt.assert_not_equal(i['source'], None)
nt.assert_equal(i['docstring'], None)
c = Call(1)
c.__doc__ = "Modified instance docstring"
i = inspector.info(c)
nt.assert_equal(i['type_name'], 'Call')
nt.assert_equal(i['docstring'], "Modified instance docstring")
nt.assert_equal(i['class_docstring'], Call.__doc__)
nt.assert_equal(i['init_docstring'], Call.__init__.__doc__)
nt.assert_equal(i['call_docstring'], c.__call__.__doc__)
# Test old-style classes, which for example may not have an __init__ method.
if not py3compat.PY3:
i = inspector.info(OldStyle)
nt.assert_equal(i['type_name'], 'classobj')
i = inspector.info(OldStyle())
nt.assert_equal(i['type_name'], 'instance')
nt.assert_equal(i['docstring'], OldStyle.__doc__)
示例11: setUp
# 需要导入模块: from IPython.utils import py3compat [as 别名]
# 或者: from IPython.utils.py3compat import PY3 [as 别名]
def setUp():
# Check we're in a proper Python 2 environment (some imports, such
# as GTK, can change the default encoding, which can hide bugs.)
nt.assert_equal(sys.getdefaultencoding(), "utf-8" if py3compat.PY3 else "ascii")
示例12: setUp
# 需要导入模块: from IPython.utils import py3compat [as 别名]
# 或者: from IPython.utils.py3compat import PY3 [as 别名]
def setUp():
nt.assert_equal(sys.getdefaultencoding(), "utf-8" if py3compat.PY3 else "ascii")
示例13: _exec_file
# 需要导入模块: from IPython.utils import py3compat [as 别名]
# 或者: from IPython.utils.py3compat import PY3 [as 别名]
def _exec_file(self, fname):
try:
full_filename = filefind(fname, [u'.', self.ipython_dir])
except IOError as e:
self.log.warn("File not found: %r"%fname)
return
# Make sure that the running script gets a proper sys.argv as if it
# were run from a system shell.
save_argv = sys.argv
sys.argv = [full_filename] + self.extra_args[1:]
# protect sys.argv from potential unicode strings on Python 2:
if not py3compat.PY3:
sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
try:
if os.path.isfile(full_filename):
self.log.info("Running file in user namespace: %s" %
full_filename)
# Ensure that __file__ is always defined to match Python
# behavior.
with preserve_keys(self.shell.user_ns, '__file__'):
self.shell.user_ns['__file__'] = fname
if full_filename.endswith('.ipy'):
self.shell.safe_execfile_ipy(full_filename)
else:
# default to python, even without extension
self.shell.safe_execfile(full_filename,
self.shell.user_ns)
finally:
sys.argv = save_argv
示例14: arg_split
# 需要导入模块: from IPython.utils import py3compat [as 别名]
# 或者: from IPython.utils.py3compat import PY3 [as 别名]
def arg_split(s, posix=False, strict=True):
"""Split a command line's arguments in a shell-like manner.
This is a modified version of the standard library's shlex.split()
function, but with a default of posix=False for splitting, so that quotes
in inputs are respected.
if strict=False, then any errors shlex.split would raise will result in the
unparsed remainder being the last element of the list, rather than raising.
This is because we sometimes use arg_split to parse things other than
command-line args.
"""
# Unfortunately, python's shlex module is buggy with unicode input:
# http://bugs.python.org/issue1170
# At least encoding the input when it's unicode seems to help, but there
# may be more problems lurking. Apparently this is fixed in python3.
is_unicode = False
if (not py3compat.PY3) and isinstance(s, unicode):
is_unicode = True
s = s.encode('utf-8')
lex = shlex.shlex(s, posix=posix)
lex.whitespace_split = True
# Extract tokens, ensuring that things like leaving open quotes
# does not cause this to raise. This is important, because we
# sometimes pass Python source through this (e.g. %timeit f(" ")),
# and it shouldn't raise an exception.
# It may be a bad idea to parse things that are not command-line args
# through this function, but we do, so let's be safe about it.
lex.commenters='' #fix for GH-1269
tokens = []
while True:
try:
tokens.append(next(lex))
except StopIteration:
break
except ValueError:
if strict:
raise
# couldn't parse, get remaining blob as last token
tokens.append(lex.token)
break
if is_unicode:
# Convert the tokens back to unicode.
tokens = [x.decode('utf-8') for x in tokens]
return tokens