本文整理匯總了Python中IPython.utils.tempdir.TemporaryDirectory方法的典型用法代碼示例。如果您正苦於以下問題:Python tempdir.TemporaryDirectory方法的具體用法?Python tempdir.TemporaryDirectory怎麽用?Python tempdir.TemporaryDirectory使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類IPython.utils.tempdir
的用法示例。
在下文中一共展示了tempdir.TemporaryDirectory方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: test_find_connection_file
# 需要導入模塊: from IPython.utils import tempdir [as 別名]
# 或者: from IPython.utils.tempdir import TemporaryDirectory [as 別名]
def test_find_connection_file():
cfg = Config()
with TemporaryDirectory() as d:
cfg.ProfileDir.location = d
cf = 'kernel.json'
app = DummyConsoleApp(config=cfg, connection_file=cf)
app.initialize(argv=[])
BaseIPythonApplication._instance = app
profile_cf = os.path.join(app.profile_dir.location, 'security', cf)
with open(profile_cf, 'w') as f:
f.write("{}")
for query in (
'kernel.json',
'kern*',
'*ernel*',
'k*',
):
nt.assert_equal(connect.find_connection_file(query), profile_cf)
BaseIPythonApplication._instance = None
示例2: test_deepreload
# 需要導入模塊: from IPython.utils import tempdir [as 別名]
# 或者: from IPython.utils.tempdir import TemporaryDirectory [as 別名]
def test_deepreload():
"Test that dreload does deep reloads and skips excluded modules."
with TemporaryDirectory() as tmpdir:
with prepended_to_syspath(tmpdir):
with open(os.path.join(tmpdir, 'A.py'), 'w') as f:
f.write("class Object(object):\n pass\n")
with open(os.path.join(tmpdir, 'B.py'), 'w') as f:
f.write("import A\n")
import A
import B
# Test that A is not reloaded.
obj = A.Object()
dreload(B, exclude=['A'])
nt.assert_true(isinstance(obj, A.Object))
# Test that A is reloaded.
obj = A.Object()
dreload(B)
nt.assert_false(isinstance(obj, A.Object))
示例3: check_handler_with_file
# 需要導入模塊: from IPython.utils import tempdir [as 別名]
# 或者: from IPython.utils.tempdir import TemporaryDirectory [as 別名]
def check_handler_with_file(self, inpath, handler):
shell = self.shell
configname = '{0}_image_handler'.format(handler)
funcname = 'handle_image_{0}'.format(handler)
assert hasattr(shell, configname)
assert hasattr(shell, funcname)
with TemporaryDirectory() as tmpdir:
outpath = os.path.join(tmpdir, 'data')
cmd = [sys.executable, SCRIPT_PATH, inpath, outpath]
setattr(shell, configname, cmd)
getattr(shell, funcname)(self.data, self.mime)
# cmd is called and file is closed. So it's safe to open now.
with open(outpath, 'rb') as file:
transferred = file.read()
self.assertEqual(transferred, self.raw)
示例4: test_changing_py_file
# 需要導入模塊: from IPython.utils import tempdir [as 別名]
# 或者: from IPython.utils.tempdir import TemporaryDirectory [as 別名]
def test_changing_py_file(self):
with TemporaryDirectory() as td:
fname = os.path.join(td, "foo.py")
with open(fname, 'w') as f:
f.write(se_file_1)
with tt.AssertPrints(["7/", "SyntaxError"]):
ip.magic("run " + fname)
# Modify the file
with open(fname, 'w') as f:
f.write(se_file_2)
# The SyntaxError should point to the correct line
with tt.AssertPrints(["7/", "SyntaxError"]):
ip.magic("run " + fname)
示例5: setUp
# 需要導入模塊: from IPython.utils import tempdir [as 別名]
# 或者: from IPython.utils.tempdir import TemporaryDirectory [as 別名]
def setUp(self):
self.package = package = 'tmp{0}'.format(repr(random.random())[2:])
"""Temporary valid python package name."""
self.value = int(random.random() * 10000)
self.tempdir = TemporaryDirectory()
self.__orig_cwd = os.getcwdu()
sys.path.insert(0, self.tempdir.name)
self.writefile(os.path.join(package, '__init__.py'), '')
self.writefile(os.path.join(package, 'sub.py'), """
x = {0!r}
""".format(self.value))
self.writefile(os.path.join(package, 'relative.py'), """
from .sub import x
""")
self.writefile(os.path.join(package, 'absolute.py'), """
from {0}.sub import x
""".format(package))
示例6: test_abspath_file_completions
# 需要導入模塊: from IPython.utils import tempdir [as 別名]
# 或者: from IPython.utils.tempdir import TemporaryDirectory [as 別名]
def test_abspath_file_completions():
ip = get_ipython()
with TemporaryDirectory() as tmpdir:
prefix = os.path.join(tmpdir, 'foo')
suffixes = map(str, [1,2])
names = [prefix+s for s in suffixes]
for n in names:
open(n, 'w').close()
# Check simple completion
c = ip.complete(prefix)[1]
nt.assert_equal(c, names)
# Now check with a function call
cmd = 'a = f("%s' % prefix
c = ip.complete(prefix, cmd)[1]
comp = [prefix+s for s in suffixes]
nt.assert_equal(c, comp)
示例7: test_local_file_completions
# 需要導入模塊: from IPython.utils import tempdir [as 別名]
# 或者: from IPython.utils.tempdir import TemporaryDirectory [as 別名]
def test_local_file_completions():
ip = get_ipython()
cwd = os.getcwdu()
try:
with TemporaryDirectory() as tmpdir:
os.chdir(tmpdir)
prefix = './foo'
suffixes = map(str, [1,2])
names = [prefix+s for s in suffixes]
for n in names:
open(n, 'w').close()
# Check simple completion
c = ip.complete(prefix)[1]
nt.assert_equal(c, names)
# Now check with a function call
cmd = 'a = f("%s' % prefix
c = ip.complete(prefix, cmd)[1]
comp = [prefix+s for s in suffixes]
nt.assert_equal(c, comp)
finally:
# prevent failures from making chdir stick
os.chdir(cwd)
示例8: test_extension
# 需要導入模塊: from IPython.utils import tempdir [as 別名]
# 或者: from IPython.utils.tempdir import TemporaryDirectory [as 別名]
def test_extension():
tmpdir = TemporaryDirectory()
orig_ipython_dir = _ip.ipython_dir
try:
_ip.ipython_dir = tmpdir.name
nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
url = os.path.join(os.path.dirname(__file__), "daft_extension.py")
_ip.magic("install_ext %s" % url)
_ip.user_ns.pop('arq', None)
invalidate_caches() # Clear import caches
_ip.magic("load_ext daft_extension")
nt.assert_equal(_ip.user_ns['arq'], 185)
_ip.magic("unload_ext daft_extension")
assert 'arq' not in _ip.user_ns
finally:
_ip.ipython_dir = orig_ipython_dir
tmpdir.cleanup()
示例9: test_file_amend
# 需要導入模塊: from IPython.utils import tempdir [as 別名]
# 或者: from IPython.utils.tempdir import TemporaryDirectory [as 別名]
def test_file_amend():
"""%%file -a amends files"""
ip = get_ipython()
with TemporaryDirectory() as td:
fname = os.path.join(td, 'file2')
ip.run_cell_magic("file", fname, u'\n'.join([
'line1',
'line2',
]))
ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
'line3',
'line4',
]))
with open(fname) as f:
s = f.read()
nt.assert_in('line1\n', s)
nt.assert_in('line3\n', s)
示例10: test_save
# 需要導入模塊: from IPython.utils import tempdir [as 別名]
# 或者: from IPython.utils.tempdir import TemporaryDirectory [as 別名]
def test_save():
"""Test %save."""
ip = get_ipython()
ip.history_manager.reset() # Clear any existing history.
cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
for i, cmd in enumerate(cmds, start=1):
ip.history_manager.store_inputs(i, cmd)
with TemporaryDirectory() as tmpdir:
file = os.path.join(tmpdir, "testsave.py")
ip.run_line_magic("save", "%s 1-10" % file)
with open(file) as f:
content = f.read()
nt.assert_equal(content.count(cmds[0]), 1)
nt.assert_in('coding: utf-8', content)
ip.run_line_magic("save", "-a %s 1-10" % file)
with open(file) as f:
content = f.read()
nt.assert_equal(content.count(cmds[0]), 2)
nt.assert_in('coding: utf-8', content)
示例11: install_my_kernel_spec
# 需要導入模塊: from IPython.utils import tempdir [as 別名]
# 或者: from IPython.utils.tempdir import TemporaryDirectory [as 別名]
def install_my_kernel_spec(user=True, prefix=None, powershell_command=None):
if sys.version_info >= (3, 0):
if powershell_command is None:
powershell_command = get_powershell()
kernel_json.update({'env': {'powershell_command' : powershell_command}})
print('Using powershell_command=%r' % powershell_command)
else:
# python 2 cannot use env to pass values to the kernel
# https://github.com/vors/jupyter-powershell/issues/7
# TODO(python2): find a way to pass it
if powershell_command is not None:
print('Ignoring powershell_command on python2, jupyter will use default powershell_command=%r' % powershell_command)
with TemporaryDirectory() as td:
os.chmod(td, 0o755) # Starts off as 700, not user readable
with open(os.path.join(td, 'kernel.json'), 'w') as f:
json.dump(kernel_json, f, sort_keys=True)
# TODO: Copy resources once they're specified
print('Installing IPython kernel spec')
KernelSpecManager().install_kernel_spec(td, 'powershell', user=user, prefix=prefix)
示例12: run
# 需要導入模塊: from IPython.utils import tempdir [as 別名]
# 或者: from IPython.utils.tempdir import TemporaryDirectory [as 別名]
def run(self):
# Regular install
install.run(self)
# Post install
print('Installing Ansible Kernel kernelspec')
from jupyter_client.kernelspec import KernelSpecManager
from IPython.utils.tempdir import TemporaryDirectory
kernel_json = {
"argv": ["python", "-m", "ansible_kernel", "-f", "{connection_file}"],
"codemirror_mode": "yaml",
"display_name": "Ansible",
"language": "ansible"
}
with TemporaryDirectory() as td:
os.chmod(td, 0o755)
with open(os.path.join(td, 'kernel.json'), 'w') as f:
json.dump(kernel_json, f, sort_keys=True)
ksm = KernelSpecManager()
ksm.install_kernel_spec(td, 'ansible', user=self.user, replace=True, prefix=self.prefix)
示例13: install_kernel_spec
# 需要導入模塊: from IPython.utils import tempdir [as 別名]
# 或者: from IPython.utils.tempdir import TemporaryDirectory [as 別名]
def install_kernel_spec(user=True, prefix=None):
from jupyter_client.kernelspec import KernelSpecManager
from IPython.utils.tempdir import TemporaryDirectory
with TemporaryDirectory() as td:
os.chmod(td, 0o755) # Starts off as 700, not user readable
with open(os.path.join(td, 'kernel.json'), 'w') as f:
json.dump(kernel_json, f, sort_keys=True)
shutil.copy2('reactivepy/images/logo-32x32.png', td)
shutil.copy2('reactivepy/images/logo-64x64.png', td)
# TODO: Copy any resources
print(f'Installing Jupyter kernel spec to {prefix}')
KernelSpecManager().install_kernel_spec(
td, 'reactivepy', user=user, prefix=prefix)
示例14: run
# 需要導入模塊: from IPython.utils import tempdir [as 別名]
# 或者: from IPython.utils.tempdir import TemporaryDirectory [as 別名]
def run(self):
install.run(self)
user = '--user' in sys.argv
try:
from jupyter_client.kernelspec import install_kernel_spec
except ImportError:
from IPython.kernel.kernelspec import install_kernel_spec
from IPython.utils.tempdir import TemporaryDirectory
with TemporaryDirectory() as td:
os.chmod(td, 0o755) # Starts off as 700, not user readable
with open(os.path.join(td, 'kernel.json'), 'w') as f:
json.dump(kernel_json, f, sort_keys=True)
log.info('Installing kernel spec')
kernel_name = kernel_json['name']
try:
install_kernel_spec(td, kernel_name, user=user,
replace=True)
except:
install_kernel_spec(td, kernel_name, user=not user,
replace=True)
示例15: convert_figure
# 需要導入模塊: from IPython.utils import tempdir [as 別名]
# 或者: from IPython.utils.tempdir import TemporaryDirectory [as 別名]
def convert_figure(self, data_format, data):
"""
Convert a single SVG figure to PDF. Returns converted data.
"""
#Work in a temporary directory
with TemporaryDirectory() as tmpdir:
#Write fig to temp file
input_filename = os.path.join(tmpdir, 'figure.' + data_format)
# SVG data is unicode text
with io.open(input_filename, 'w', encoding='utf8') as f:
f.write(data)
#Call conversion application
output_filename = os.path.join(tmpdir, 'figure.pdf')
shell = self.command.format(from_filename=input_filename,
to_filename=output_filename)
subprocess.call(shell, shell=True) #Shell=True okay since input is trusted.
#Read output from drive
# return value expects a filename
if os.path.isfile(output_filename):
with open(output_filename, 'rb') as f:
# PDF is a nb supported binary, data type, so base64 encode.
return base64.encodestring(f.read())
else:
raise TypeError("Inkscape svg to png conversion failed")