##// END OF EJS Templates
Merge pull request #4469 from takluyver/py3-getcwdu...
Min RK -
r13456:5bf4949f merge
parent child Browse files
Show More
@@ -40,6 +40,7 b' from IPython.config.loader import ConfigFileNotFound'
40 from IPython.core import release, crashhandler
40 from IPython.core import release, crashhandler
41 from IPython.core.profiledir import ProfileDir, ProfileDirError
41 from IPython.core.profiledir import ProfileDir, ProfileDirError
42 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir
42 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir
43 from IPython.utils import py3compat
43 from IPython.utils.traitlets import List, Unicode, Type, Bool, Dict, Set, Instance
44 from IPython.utils.traitlets import List, Unicode, Type, Bool, Dict, Set, Instance
44
45
45 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
@@ -103,7 +104,7 b' class BaseIPythonApplication(Application):'
103
104
104 config_file_paths = List(Unicode)
105 config_file_paths = List(Unicode)
105 def _config_file_paths_default(self):
106 def _config_file_paths_default(self):
106 return [os.getcwdu()]
107 return [py3compat.getcwd()]
107
108
108 extra_config_file = Unicode(config=True,
109 extra_config_file = Unicode(config=True,
109 help="""Path to an extra config file to load.
110 help="""Path to an extra config file to load.
@@ -179,7 +180,7 b' class BaseIPythonApplication(Application):'
179 super(BaseIPythonApplication, self).__init__(**kwargs)
180 super(BaseIPythonApplication, self).__init__(**kwargs)
180 # ensure current working directory exists
181 # ensure current working directory exists
181 try:
182 try:
182 directory = os.getcwdu()
183 directory = py3compat.getcwd()
183 except:
184 except:
184 # raise exception
185 # raise exception
185 self.log.error("Current working directory doesn't exist.")
186 self.log.error("Current working directory doesn't exist.")
@@ -28,7 +28,7 b' from pprint import pformat'
28 from IPython.core import ultratb
28 from IPython.core import ultratb
29 from IPython.core.release import author_email
29 from IPython.core.release import author_email
30 from IPython.utils.sysinfo import sys_info
30 from IPython.utils.sysinfo import sys_info
31 from IPython.utils.py3compat import input
31 from IPython.utils.py3compat import input, getcwd
32
32
33 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
34 # Code
34 # Code
@@ -140,9 +140,9 b' class CrashHandler(object):'
140 try:
140 try:
141 rptdir = self.app.ipython_dir
141 rptdir = self.app.ipython_dir
142 except:
142 except:
143 rptdir = os.getcwdu()
143 rptdir = getcwd()
144 if rptdir is None or not os.path.isdir(rptdir):
144 if rptdir is None or not os.path.isdir(rptdir):
145 rptdir = os.getcwdu()
145 rptdir = getcwd()
146 report_name = os.path.join(rptdir,self.crash_report_fname)
146 report_name = os.path.join(rptdir,self.crash_report_fname)
147 # write the report filename into the instance dict so it can get
147 # write the report filename into the instance dict so it can get
148 # properly expanded out in the user message template
148 # properly expanded out in the user message template
@@ -30,6 +30,7 b' import threading'
30 from IPython.config.configurable import Configurable
30 from IPython.config.configurable import Configurable
31 from IPython.external.decorator import decorator
31 from IPython.external.decorator import decorator
32 from IPython.utils.path import locate_profile
32 from IPython.utils.path import locate_profile
33 from IPython.utils import py3compat
33 from IPython.utils.traitlets import (
34 from IPython.utils.traitlets import (
34 Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
35 Any, Bool, Dict, Instance, Integer, List, Unicode, TraitError,
35 )
36 )
@@ -423,7 +424,7 b' class HistoryManager(HistoryAccessor):'
423 dir_hist = List()
424 dir_hist = List()
424 def _dir_hist_default(self):
425 def _dir_hist_default(self):
425 try:
426 try:
426 return [os.getcwdu()]
427 return [py3compat.getcwd()]
427 except OSError:
428 except OSError:
428 return []
429 return []
429
430
@@ -519,7 +520,7 b' class HistoryManager(HistoryAccessor):'
519 optionally open a new session."""
520 optionally open a new session."""
520 self.output_hist.clear()
521 self.output_hist.clear()
521 # The directory history can't be completely empty
522 # The directory history can't be completely empty
522 self.dir_hist[:] = [os.getcwdu()]
523 self.dir_hist[:] = [py3compat.getcwd()]
523
524
524 if new_session:
525 if new_session:
525 if self.session_number:
526 if self.session_number:
@@ -578,7 +578,7 b' class InteractiveShell(SingletonConfigurable):'
578
578
579 # keep track of where we started running (mainly for crash post-mortem)
579 # keep track of where we started running (mainly for crash post-mortem)
580 # This is not being used anywhere currently.
580 # This is not being used anywhere currently.
581 self.starting_dir = os.getcwdu()
581 self.starting_dir = py3compat.getcwd()
582
582
583 # Indentation management
583 # Indentation management
584 self.indent_current_nsp = 0
584 self.indent_current_nsp = 0
@@ -36,6 +36,7 b' from IPython.testing.skipdoctest import skip_doctest'
36 from IPython.utils.openpy import source_to_unicode
36 from IPython.utils.openpy import source_to_unicode
37 from IPython.utils.path import unquote_filename
37 from IPython.utils.path import unquote_filename
38 from IPython.utils.process import abbrev_cwd
38 from IPython.utils.process import abbrev_cwd
39 from IPython.utils import py3compat
39 from IPython.utils.py3compat import unicode_type
40 from IPython.utils.py3compat import unicode_type
40 from IPython.utils.terminal import set_term_title
41 from IPython.utils.terminal import set_term_title
41
42
@@ -180,7 +181,7 b' class OSMagics(Magics):'
180 winext += '|py'
181 winext += '|py'
181 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
182 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
182 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
183 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
183 savedir = os.getcwdu()
184 savedir = py3compat.getcwd()
184
185
185 # Now walk the paths looking for executables to alias.
186 # Now walk the paths looking for executables to alias.
186 try:
187 try:
@@ -234,7 +235,7 b' class OSMagics(Magics):'
234 In [9]: pwd
235 In [9]: pwd
235 Out[9]: '/home/tsuser/sprint/ipython'
236 Out[9]: '/home/tsuser/sprint/ipython'
236 """
237 """
237 return os.getcwdu()
238 return py3compat.getcwd()
238
239
239 @skip_doctest
240 @skip_doctest
240 @line_magic
241 @line_magic
@@ -278,7 +279,7 b' class OSMagics(Magics):'
278 /home/tsuser/parent/child
279 /home/tsuser/parent/child
279 """
280 """
280
281
281 oldcwd = os.getcwdu()
282 oldcwd = py3compat.getcwd()
282 numcd = re.match(r'(-)(\d+)$',parameter_s)
283 numcd = re.match(r'(-)(\d+)$',parameter_s)
283 # jump in directory history by number
284 # jump in directory history by number
284 if numcd:
285 if numcd:
@@ -351,7 +352,7 b' class OSMagics(Magics):'
351 except OSError:
352 except OSError:
352 print(sys.exc_info()[1])
353 print(sys.exc_info()[1])
353 else:
354 else:
354 cwd = os.getcwdu()
355 cwd = py3compat.getcwd()
355 dhist = self.shell.user_ns['_dh']
356 dhist = self.shell.user_ns['_dh']
356 if oldcwd != cwd:
357 if oldcwd != cwd:
357 dhist.append(cwd)
358 dhist.append(cwd)
@@ -361,7 +362,7 b' class OSMagics(Magics):'
361 os.chdir(self.shell.home_dir)
362 os.chdir(self.shell.home_dir)
362 if hasattr(self.shell, 'term_title') and self.shell.term_title:
363 if hasattr(self.shell, 'term_title') and self.shell.term_title:
363 set_term_title('IPython: ' + '~')
364 set_term_title('IPython: ' + '~')
364 cwd = os.getcwdu()
365 cwd = py3compat.getcwd()
365 dhist = self.shell.user_ns['_dh']
366 dhist = self.shell.user_ns['_dh']
366
367
367 if oldcwd != cwd:
368 if oldcwd != cwd:
@@ -387,7 +388,7 b' class OSMagics(Magics):'
387
388
388 dir_s = self.shell.dir_stack
389 dir_s = self.shell.dir_stack
389 tgt = os.path.expanduser(unquote_filename(parameter_s))
390 tgt = os.path.expanduser(unquote_filename(parameter_s))
390 cwd = os.getcwdu().replace(self.shell.home_dir,'~')
391 cwd = py3compat.getcwd().replace(self.shell.home_dir,'~')
391 if tgt:
392 if tgt:
392 self.cd(parameter_s)
393 self.cd(parameter_s)
393 dir_s.insert(0,cwd)
394 dir_s.insert(0,cwd)
@@ -676,7 +677,7 b' class OSMagics(Magics):'
676 if not args:
677 if not args:
677 raise UsageError("%bookmark: You must specify the bookmark name")
678 raise UsageError("%bookmark: You must specify the bookmark name")
678 elif len(args)==1:
679 elif len(args)==1:
679 bkms[args[0]] = os.getcwdu()
680 bkms[args[0]] = py3compat.getcwd()
680 elif len(args)==2:
681 elif len(args)==2:
681 bkms[args[0]] = args[1]
682 bkms[args[0]] = args[1]
682 self.shell.db['bookmarks'] = bkms
683 self.shell.db['bookmarks'] = bkms
@@ -31,6 +31,7 b' from IPython.core.application import ('
31 from IPython.core.profiledir import ProfileDir
31 from IPython.core.profiledir import ProfileDir
32 from IPython.utils.importstring import import_item
32 from IPython.utils.importstring import import_item
33 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir
33 from IPython.utils.path import get_ipython_dir, get_ipython_package_dir
34 from IPython.utils import py3compat
34 from IPython.utils.traitlets import Unicode, Bool, Dict
35 from IPython.utils.traitlets import Unicode, Bool, Dict
35
36
36 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
@@ -180,10 +181,10 b' class ProfileList(Application):'
180 print("Available profiles in %s:" % self.ipython_dir)
181 print("Available profiles in %s:" % self.ipython_dir)
181 self._print_profiles(profiles)
182 self._print_profiles(profiles)
182
183
183 profiles = list_profiles_in(os.getcwdu())
184 profiles = list_profiles_in(py3compat.getcwd())
184 if profiles:
185 if profiles:
185 print()
186 print()
186 print("Available profiles in current directory (%s):" % os.getcwdu())
187 print("Available profiles in current directory (%s):" % py3compat.getcwd())
187 self._print_profiles(profiles)
188 self._print_profiles(profiles)
188
189
189 print()
190 print()
@@ -248,7 +249,7 b' class ProfileCreate(BaseIPythonApplication):'
248 name = app_path.rsplit('.', 1)[-1]
249 name = app_path.rsplit('.', 1)[-1]
249 try:
250 try:
250 app = import_item(app_path)
251 app = import_item(app_path)
251 except ImportError as e:
252 except ImportError:
252 self.log.info("Couldn't import %s, config file will be excluded", name)
253 self.log.info("Couldn't import %s, config file will be excluded", name)
253 except Exception:
254 except Exception:
254 self.log.warn('Unexpected error importing %s', name, exc_info=True)
255 self.log.warn('Unexpected error importing %s', name, exc_info=True)
@@ -27,6 +27,7 b' import errno'
27
27
28 from IPython.config.configurable import LoggingConfigurable
28 from IPython.config.configurable import LoggingConfigurable
29 from IPython.utils.path import get_ipython_package_dir, expand_path
29 from IPython.utils.path import get_ipython_package_dir, expand_path
30 from IPython.utils import py3compat
30 from IPython.utils.traitlets import Unicode, Bool
31 from IPython.utils.traitlets import Unicode, Bool
31
32
32 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
@@ -233,7 +234,7 b' class ProfileDir(LoggingConfigurable):'
233 is not found, a :class:`ProfileDirError` exception will be raised.
234 is not found, a :class:`ProfileDirError` exception will be raised.
234
235
235 The search path algorithm is:
236 The search path algorithm is:
236 1. ``os.getcwdu()``
237 1. ``py3compat.getcwd()``
237 2. ``ipython_dir``
238 2. ``ipython_dir``
238
239
239 Parameters
240 Parameters
@@ -245,7 +246,7 b' class ProfileDir(LoggingConfigurable):'
245 will be "profile_<profile>".
246 will be "profile_<profile>".
246 """
247 """
247 dirname = u'profile_' + name
248 dirname = u'profile_' + name
248 paths = [os.getcwdu(), ipython_dir]
249 paths = [py3compat.getcwd(), ipython_dir]
249 for p in paths:
250 for p in paths:
250 profile_dir = os.path.join(p, dirname)
251 profile_dir = os.path.join(p, dirname)
251 if os.path.isdir(profile_dir):
252 if os.path.isdir(profile_dir):
@@ -212,7 +212,7 b' def cwd_filt(depth):'
212 $HOME is always replaced with '~'.
212 $HOME is always replaced with '~'.
213 If depth==0, the full path is returned."""
213 If depth==0, the full path is returned."""
214
214
215 cwd = os.getcwdu().replace(HOME,"~")
215 cwd = py3compat.getcwd().replace(HOME,"~")
216 out = os.sep.join(cwd.split(os.sep)[-depth:])
216 out = os.sep.join(cwd.split(os.sep)[-depth:])
217 return out or os.sep
217 return out or os.sep
218
218
@@ -222,7 +222,7 b' def cwd_filt2(depth):'
222 $HOME is always replaced with '~'.
222 $HOME is always replaced with '~'.
223 If depth==0, the full path is returned."""
223 If depth==0, the full path is returned."""
224
224
225 full_cwd = os.getcwdu()
225 full_cwd = py3compat.getcwd()
226 cwd = full_cwd.replace(HOME,"~").split(os.sep)
226 cwd = full_cwd.replace(HOME,"~").split(os.sep)
227 if '~' in cwd and len(cwd) == depth+1:
227 if '~' in cwd and len(cwd) == depth+1:
228 depth += 1
228 depth += 1
@@ -238,9 +238,9 b' def cwd_filt2(depth):'
238 #-----------------------------------------------------------------------------
238 #-----------------------------------------------------------------------------
239
239
240 lazily_evaluate = {'time': LazyEvaluate(time.strftime, "%H:%M:%S"),
240 lazily_evaluate = {'time': LazyEvaluate(time.strftime, "%H:%M:%S"),
241 'cwd': LazyEvaluate(os.getcwdu),
241 'cwd': LazyEvaluate(py3compat.getcwd),
242 'cwd_last': LazyEvaluate(lambda: os.getcwdu().split(os.sep)[-1]),
242 'cwd_last': LazyEvaluate(lambda: py3compat.getcwd().split(os.sep)[-1]),
243 'cwd_x': [LazyEvaluate(lambda: os.getcwdu().replace(HOME,"~"))] +\
243 'cwd_x': [LazyEvaluate(lambda: py3compat.getcwd().replace(HOME,"~"))] +\
244 [LazyEvaluate(cwd_filt, x) for x in range(1,6)],
244 [LazyEvaluate(cwd_filt, x) for x in range(1,6)],
245 'cwd_y': [LazyEvaluate(cwd_filt2, x) for x in range(6)]
245 'cwd_y': [LazyEvaluate(cwd_filt2, x) for x in range(6)]
246 }
246 }
@@ -13,9 +13,9 b' def test_unicode_cwd():'
13 """Check that IPython starts with non-ascii characters in the path."""
13 """Check that IPython starts with non-ascii characters in the path."""
14 wd = tempfile.mkdtemp(suffix=u"€")
14 wd = tempfile.mkdtemp(suffix=u"€")
15
15
16 old_wd = os.getcwdu()
16 old_wd = py3compat.getcwd()
17 os.chdir(wd)
17 os.chdir(wd)
18 #raise Exception(repr(os.getcwdu()))
18 #raise Exception(repr(py3compat.getcwd()))
19 try:
19 try:
20 app = BaseIPythonApplication()
20 app = BaseIPythonApplication()
21 # The lines below are copied from Application.initialize()
21 # The lines below are copied from Application.initialize()
@@ -18,6 +18,7 b' from IPython.core import completer'
18 from IPython.external.decorators import knownfailureif
18 from IPython.external.decorators import knownfailureif
19 from IPython.utils.tempdir import TemporaryDirectory
19 from IPython.utils.tempdir import TemporaryDirectory
20 from IPython.utils.generics import complete_object
20 from IPython.utils.generics import complete_object
21 from IPython.utils import py3compat
21 from IPython.utils.py3compat import string_types, unicode_type
22 from IPython.utils.py3compat import string_types, unicode_type
22
23
23 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
@@ -177,7 +178,7 b' def test_abspath_file_completions():'
177
178
178 def test_local_file_completions():
179 def test_local_file_completions():
179 ip = get_ipython()
180 ip = get_ipython()
180 cwd = os.getcwdu()
181 cwd = py3compat.getcwd()
181 try:
182 try:
182 with TemporaryDirectory() as tmpdir:
183 with TemporaryDirectory() as tmpdir:
183 os.chdir(tmpdir)
184 os.chdir(tmpdir)
@@ -16,6 +16,7 b' import unittest'
16 from os.path import join
16 from os.path import join
17
17
18 from IPython.core.completerlib import magic_run_completer, module_completion
18 from IPython.core.completerlib import magic_run_completer, module_completion
19 from IPython.utils import py3compat
19 from IPython.utils.tempdir import TemporaryDirectory
20 from IPython.utils.tempdir import TemporaryDirectory
20 from IPython.testing.decorators import onlyif_unicode_paths
21 from IPython.testing.decorators import onlyif_unicode_paths
21
22
@@ -33,7 +34,7 b' class Test_magic_run_completer(unittest.TestCase):'
33 for fil in [u"aao.py", u"a.py", u"b.py"]:
34 for fil in [u"aao.py", u"a.py", u"b.py"]:
34 with open(join(self.BASETESTDIR, fil), "w") as sfile:
35 with open(join(self.BASETESTDIR, fil), "w") as sfile:
35 sfile.write("pass\n")
36 sfile.write("pass\n")
36 self.oldpath = os.getcwdu()
37 self.oldpath = py3compat.getcwd()
37 os.chdir(self.BASETESTDIR)
38 os.chdir(self.BASETESTDIR)
38
39
39 def tearDown(self):
40 def tearDown(self):
@@ -86,7 +87,7 b' class Test_magic_run_completer_nonascii(unittest.TestCase):'
86 for fil in [u"aaø.py", u"a.py", u"b.py"]:
87 for fil in [u"aaø.py", u"a.py", u"b.py"]:
87 with open(join(self.BASETESTDIR, fil), "w") as sfile:
88 with open(join(self.BASETESTDIR, fil), "w") as sfile:
88 sfile.write("pass\n")
89 sfile.write("pass\n")
89 self.oldpath = os.getcwdu()
90 self.oldpath = py3compat.getcwd()
90 os.chdir(self.BASETESTDIR)
91 os.chdir(self.BASETESTDIR)
91
92
92 def tearDown(self):
93 def tearDown(self):
@@ -36,6 +36,7 b' import nose.tools as nt'
36 from IPython.testing.decorators import skipif, skip_win32, onlyif_unicode_paths
36 from IPython.testing.decorators import skipif, skip_win32, onlyif_unicode_paths
37 from IPython.testing import tools as tt
37 from IPython.testing import tools as tt
38 from IPython.utils import io
38 from IPython.utils import io
39 from IPython.utils import py3compat
39 from IPython.utils.py3compat import unicode_type, PY3
40 from IPython.utils.py3compat import unicode_type, PY3
40
41
41 if PY3:
42 if PY3:
@@ -406,7 +407,7 b' class TestSafeExecfileNonAsciiPath(unittest.TestCase):'
406 os.mkdir(self.TESTDIR)
407 os.mkdir(self.TESTDIR)
407 with open(join(self.TESTDIR, u"åäötestscript.py"), "w") as sfile:
408 with open(join(self.TESTDIR, u"åäötestscript.py"), "w") as sfile:
408 sfile.write("pass\n")
409 sfile.write("pass\n")
409 self.oldpath = os.getcwdu()
410 self.oldpath = py3compat.getcwd()
410 os.chdir(self.TESTDIR)
411 os.chdir(self.TESTDIR)
411 self.fname = u"åäötestscript.py"
412 self.fname = u"åäötestscript.py"
412
413
@@ -390,9 +390,9 b' def test_parse_options():'
390
390
391 def test_dirops():
391 def test_dirops():
392 """Test various directory handling operations."""
392 """Test various directory handling operations."""
393 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
393 # curpath = lambda :os.path.splitdrive(py3compat.getcwd())[1].replace('\\','/')
394 curpath = os.getcwdu
394 curpath = py3compat.getcwd
395 startdir = os.getcwdu()
395 startdir = py3compat.getcwd()
396 ipdir = os.path.realpath(_ip.ipython_dir)
396 ipdir = os.path.realpath(_ip.ipython_dir)
397 try:
397 try:
398 _ip.magic('cd "%s"' % ipdir)
398 _ip.magic('cd "%s"' % ipdir)
@@ -9,6 +9,7 b' from IPython.testing import tools as tt, decorators as dec'
9 from IPython.core.prompts import PromptManager, LazyEvaluate
9 from IPython.core.prompts import PromptManager, LazyEvaluate
10 from IPython.testing.globalipapp import get_ipython
10 from IPython.testing.globalipapp import get_ipython
11 from IPython.utils.tempdir import TemporaryDirectory
11 from IPython.utils.tempdir import TemporaryDirectory
12 from IPython.utils import py3compat
12 from IPython.utils.py3compat import unicode_type
13 from IPython.utils.py3compat import unicode_type
13
14
14 ip = get_ipython()
15 ip = get_ipython()
@@ -66,12 +67,12 b' class PromptTests(unittest.TestCase):'
66
67
67 @dec.onlyif_unicode_paths
68 @dec.onlyif_unicode_paths
68 def test_render_unicode_cwd(self):
69 def test_render_unicode_cwd(self):
69 save = os.getcwdu()
70 save = py3compat.getcwd()
70 with TemporaryDirectory(u'ünicødé') as td:
71 with TemporaryDirectory(u'ünicødé') as td:
71 os.chdir(td)
72 os.chdir(td)
72 self.pm.in_template = r'\w [\#]'
73 self.pm.in_template = r'\w [\#]'
73 p = self.pm.render('in', color=False)
74 p = self.pm.render('in', color=False)
74 self.assertEqual(p, u"%s [%i]" % (os.getcwdu(), ip.execution_count))
75 self.assertEqual(p, u"%s [%i]" % (py3compat.getcwd(), ip.execution_count))
75 os.chdir(save)
76 os.chdir(save)
76
77
77 def test_lazy_eval_unicode(self):
78 def test_lazy_eval_unicode(self):
@@ -101,7 +102,7 b' class PromptTests(unittest.TestCase):'
101 @dec.skip_win32
102 @dec.skip_win32
102 def test_cwd_x(self):
103 def test_cwd_x(self):
103 self.pm.in_template = r"\X0"
104 self.pm.in_template = r"\X0"
104 save = os.getcwdu()
105 save = py3compat.getcwd()
105 os.chdir(os.path.expanduser('~'))
106 os.chdir(os.path.expanduser('~'))
106 p = self.pm.render('in', color=False)
107 p = self.pm.render('in', color=False)
107 try:
108 try:
@@ -390,7 +390,7 b' class TestMagicRunWithPackage(unittest.TestCase):'
390 self.value = int(random.random() * 10000)
390 self.value = int(random.random() * 10000)
391
391
392 self.tempdir = TemporaryDirectory()
392 self.tempdir = TemporaryDirectory()
393 self.__orig_cwd = os.getcwdu()
393 self.__orig_cwd = py3compat.getcwd()
394 sys.path.insert(0, self.tempdir.name)
394 sys.path.insert(0, self.tempdir.name)
395
395
396 self.writefile(os.path.join(package, '__init__.py'), '')
396 self.writefile(os.path.join(package, '__init__.py'), '')
@@ -84,9 +84,9 b' except NameError:'
84 unicode = str
84 unicode = str
85
85
86 try:
86 try:
87 os.getcwdu
87 getcwdu = os.getcwdu
88 except AttributeError:
88 except AttributeError:
89 os.getcwdu = os.getcwd
89 getcwdu = os.getcwd
90
90
91 if sys.version < '3':
91 if sys.version < '3':
92 def u(x):
92 def u(x):
@@ -214,7 +214,7 b' class path(unicode):'
214 @classmethod
214 @classmethod
215 def getcwd(cls):
215 def getcwd(cls):
216 """ Return the current working directory as a path object. """
216 """ Return the current working directory as a path object. """
217 return cls(os.getcwdu())
217 return cls(getcwdu())
218
218
219 #
219 #
220 # --- Operations on path strings.
220 # --- Operations on path strings.
@@ -16,8 +16,6 b' Authors:'
16 # Imports
16 # Imports
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 import os
20
21 from tornado import web
19 from tornado import web
22 from zmq.eventloop import ioloop
20 from zmq.eventloop import ioloop
23
21
@@ -26,6 +24,7 b' from IPython.utils.traitlets import Dict, Instance, CFloat'
26 from IPython.parallel.apps.ipclusterapp import IPClusterStart
24 from IPython.parallel.apps.ipclusterapp import IPClusterStart
27 from IPython.core.profileapp import list_profiles_in
25 from IPython.core.profileapp import list_profiles_in
28 from IPython.core.profiledir import ProfileDir
26 from IPython.core.profiledir import ProfileDir
27 from IPython.utils import py3compat
29 from IPython.utils.path import get_ipython_dir
28 from IPython.utils.path import get_ipython_dir
30
29
31
30
@@ -74,7 +73,7 b' class ClusterManager(LoggingConfigurable):'
74 def update_profiles(self):
73 def update_profiles(self):
75 """List all profiles in the ipython_dir and cwd.
74 """List all profiles in the ipython_dir and cwd.
76 """
75 """
77 for path in [get_ipython_dir(), os.getcwdu()]:
76 for path in [get_ipython_dir(), py3compat.getcwd()]:
78 for profile in list_profiles_in(path):
77 for profile in list_profiles_in(path):
79 pd = self.get_profile_dir(profile, path)
78 pd = self.get_profile_dir(profile, path)
80 if profile not in self.profiles:
79 if profile not in self.profiles:
@@ -21,7 +21,8 b' import os'
21
21
22 from IPython.config.configurable import LoggingConfigurable
22 from IPython.config.configurable import LoggingConfigurable
23 from IPython.nbformat import current
23 from IPython.nbformat import current
24 from IPython.utils.traitlets import List, Dict, Unicode, TraitError
24 from IPython.utils import py3compat
25 from IPython.utils.traitlets import Unicode, TraitError
25
26
26 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
27 # Classes
28 # Classes
@@ -35,7 +36,7 b' class NotebookManager(LoggingConfigurable):'
35 # 2. The cwd of the kernel for a project.
36 # 2. The cwd of the kernel for a project.
36 # Right now we use this attribute in a number of different places and
37 # Right now we use this attribute in a number of different places and
37 # we are going to have to disentangle all of this.
38 # we are going to have to disentangle all of this.
38 notebook_dir = Unicode(os.getcwdu(), config=True, help="""
39 notebook_dir = Unicode(py3compat.getcwd(), config=True, help="""
39 The directory to use for notebooks.
40 The directory to use for notebooks.
40 """)
41 """)
41
42
@@ -36,6 +36,7 b' from IPython.core.application import ('
36 base_flags as base_ip_flags
36 base_flags as base_ip_flags
37 )
37 )
38 from IPython.utils.path import expand_path
38 from IPython.utils.path import expand_path
39 from IPython.utils import py3compat
39 from IPython.utils.py3compat import unicode_type
40 from IPython.utils.py3compat import unicode_type
40
41
41 from IPython.utils.traitlets import Unicode, Bool, Instance, Dict
42 from IPython.utils.traitlets import Unicode, Bool, Instance, Dict
@@ -105,7 +106,7 b' class BaseParallelApplication(BaseIPythonApplication):'
105 """override default log format to include time"""
106 """override default log format to include time"""
106 return u"%(asctime)s.%(msecs).03d [%(name)s]%(highlevel)s %(message)s"
107 return u"%(asctime)s.%(msecs).03d [%(name)s]%(highlevel)s %(message)s"
107
108
108 work_dir = Unicode(os.getcwdu(), config=True,
109 work_dir = Unicode(py3compat.getcwd(), config=True,
109 help='Set the working dir for the process.'
110 help='Set the working dir for the process.'
110 )
111 )
111 def _work_dir_changed(self, name, old, new):
112 def _work_dir_changed(self, name, old, new):
@@ -156,7 +157,7 b' class BaseParallelApplication(BaseIPythonApplication):'
156
157
157 def to_work_dir(self):
158 def to_work_dir(self):
158 wd = self.work_dir
159 wd = self.work_dir
159 if unicode_type(wd) != os.getcwdu():
160 if unicode_type(wd) != py3compat.getcwd():
160 os.chdir(wd)
161 os.chdir(wd)
161 self.log.info("Changing to working dir: %s" % wd)
162 self.log.info("Changing to working dir: %s" % wd)
162 # This is the working dir by now.
163 # This is the working dir by now.
@@ -45,7 +45,7 b' from nose.plugins import doctests, Plugin'
45 from nose.util import anyp, getpackage, test_address, resolve_name, tolist
45 from nose.util import anyp, getpackage, test_address, resolve_name, tolist
46
46
47 # Our own imports
47 # Our own imports
48 from IPython.utils.py3compat import builtin_mod, PY3
48 from IPython.utils.py3compat import builtin_mod, PY3, getcwd
49
49
50 if PY3:
50 if PY3:
51 from io import StringIO
51 from io import StringIO
@@ -255,7 +255,7 b' class DocTestCase(doctests.DocTestCase):'
255 # Save our current directory and switch out to the one where the
255 # Save our current directory and switch out to the one where the
256 # test was originally created, in case another doctest did a
256 # test was originally created, in case another doctest did a
257 # directory change. We'll restore this in the finally clause.
257 # directory change. We'll restore this in the finally clause.
258 curdir = os.getcwdu()
258 curdir = getcwd()
259 #print 'runTest in dir:', self._ori_dir # dbg
259 #print 'runTest in dir:', self._ori_dir # dbg
260 os.chdir(self._ori_dir)
260 os.chdir(self._ori_dir)
261
261
@@ -54,7 +54,7 b' class AvoidUNCPath(object):'
54 os.system(cmd)
54 os.system(cmd)
55 """
55 """
56 def __enter__(self):
56 def __enter__(self):
57 self.path = os.getcwdu()
57 self.path = py3compat.getcwd()
58 self.is_unc_path = self.path.startswith(r"\\")
58 self.is_unc_path = self.path.startswith(r"\\")
59 if self.is_unc_path:
59 if self.is_unc_path:
60 # change to c drive (as cmd.exe cannot handle UNC addresses)
60 # change to c drive (as cmd.exe cannot handle UNC addresses)
@@ -17,7 +17,7 b' import os, sys, threading'
17 import ctypes, msvcrt
17 import ctypes, msvcrt
18
18
19 # local imports
19 # local imports
20 from .py3compat import unicode_type
20 from . import py3compat
21
21
22 # Win32 API types needed for the API calls
22 # Win32 API types needed for the API calls
23 from ctypes import POINTER
23 from ctypes import POINTER
@@ -174,7 +174,7 b' class AvoidUNCPath(object):'
174 os.system(cmd)
174 os.system(cmd)
175 """
175 """
176 def __enter__(self):
176 def __enter__(self):
177 self.path = os.getcwdu()
177 self.path = py3compat.getcwd()
178 self.is_unc_path = self.path.startswith(r"\\")
178 self.is_unc_path = self.path.startswith(r"\\")
179 if self.is_unc_path:
179 if self.is_unc_path:
180 # change to c drive (as cmd.exe cannot handle UNC addresses)
180 # change to c drive (as cmd.exe cannot handle UNC addresses)
@@ -166,7 +166,7 b' def filefind(filename, path_dirs=None):'
166 path_dirs = (path_dirs,)
166 path_dirs = (path_dirs,)
167
167
168 for path in path_dirs:
168 for path in path_dirs:
169 if path == '.': path = os.getcwdu()
169 if path == '.': path = py3compat.getcwd()
170 testname = expand_path(os.path.join(path, filename))
170 testname = expand_path(os.path.join(path, filename))
171 if os.path.isfile(testname):
171 if os.path.isfile(testname):
172 return os.path.abspath(testname)
172 return os.path.abspath(testname)
@@ -28,6 +28,7 b' else:'
28
28
29
29
30 from ._process_common import getoutputerror, get_output_error_code
30 from ._process_common import getoutputerror, get_output_error_code
31 from . import py3compat
31
32
32 #-----------------------------------------------------------------------------
33 #-----------------------------------------------------------------------------
33 # Code
34 # Code
@@ -105,7 +106,7 b' def pycmd2argv(cmd):'
105
106
106 def abbrev_cwd():
107 def abbrev_cwd():
107 """ Return abbreviated version of cwd, e.g. d:mydir """
108 """ Return abbreviated version of cwd, e.g. d:mydir """
108 cwd = os.getcwdu().replace('\\','/')
109 cwd = py3compat.getcwd().replace('\\','/')
109 drivepart = ''
110 drivepart = ''
110 tail = cwd
111 tail = cwd
111 if sys.platform == 'win32':
112 if sys.platform == 'win32':
@@ -1,6 +1,7 b''
1 # coding: utf-8
1 # coding: utf-8
2 """Compatibility tricks for Python 3. Mainly to do with unicode."""
2 """Compatibility tricks for Python 3. Mainly to do with unicode."""
3 import functools
3 import functools
4 import os
4 import sys
5 import sys
5 import re
6 import re
6 import types
7 import types
@@ -95,6 +96,7 b' if sys.version_info[0] >= 3:'
95 xrange = range
96 xrange = range
96 def iteritems(d): return iter(d.items())
97 def iteritems(d): return iter(d.items())
97 def itervalues(d): return iter(d.values())
98 def itervalues(d): return iter(d.values())
99 getcwd = os.getcwd
98
100
99 MethodType = types.MethodType
101 MethodType = types.MethodType
100
102
@@ -172,6 +174,7 b' else:'
172 xrange = xrange
174 xrange = xrange
173 def iteritems(d): return d.iteritems()
175 def iteritems(d): return d.iteritems()
174 def itervalues(d): return d.itervalues()
176 def itervalues(d): return d.itervalues()
177 getcwd = os.getcwdu
175
178
176 def MethodType(func, instance):
179 def MethodType(func, instance):
177 return types.MethodType(func, instance, type(instance))
180 return types.MethodType(func, instance, type(instance))
@@ -25,6 +25,8 b' import struct'
25 import sys
25 import sys
26 import warnings
26 import warnings
27
27
28 from . import py3compat
29
28 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
29 # Code
31 # Code
30 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
@@ -102,7 +104,7 b" if sys.platform == 'win32':"
102
104
103 try:
105 try:
104 # Cannot be on network share when issuing system commands
106 # Cannot be on network share when issuing system commands
105 curr = os.getcwdu()
107 curr = py3compat.getcwd()
106 os.chdir("C:")
108 os.chdir("C:")
107 ret = os.system("title " + title)
109 ret = os.system("title " + title)
108 finally:
110 finally:
@@ -523,7 +523,7 b' class TestShellGlob(object):'
523 @classmethod
523 @classmethod
524 @contextmanager
524 @contextmanager
525 def in_tempdir(cls):
525 def in_tempdir(cls):
526 save = os.getcwdu()
526 save = py3compat.getcwd()
527 try:
527 try:
528 os.chdir(cls.tempdir.name)
528 os.chdir(cls.tempdir.name)
529 yield
529 yield
General Comments 0
You need to be logged in to leave comments. Login now