##// END OF EJS Templates
All code startup related things are working....
Brian Granger -
Show More
@@ -275,6 +275,12 b' class ArgParseConfigLoader(CommandLineConfigLoader):'
275 275 self._convert_to_config()
276 276 return self.config
277 277
278 def get_extra_args(self):
279 if hasattr(self, 'extra_args'):
280 return self.extra_args
281 else:
282 return []
283
278 284 def _create_parser(self):
279 285 self.parser = argparse.ArgumentParser(*self.args, **self.kw)
280 286 self._add_arguments()
@@ -292,9 +298,9 b' class ArgParseConfigLoader(CommandLineConfigLoader):'
292 298 def _parse_args(self, args=None):
293 299 """self.parser->self.parsed_data"""
294 300 if args is None:
295 self.parsed_data = self.parser.parse_args()
301 self.parsed_data, self.extra_args = self.parser.parse_known_args()
296 302 else:
297 self.parsed_data = self.parser.parse_args(args)
303 self.parsed_data, self.extra_args = self.parser.parse_known_args(args)
298 304
299 305 def _convert_to_config(self):
300 306 """self.parsed_data->self.config"""
@@ -117,7 +117,14 b' class Application(object):'
117 117 #-------------------------------------------------------------------------
118 118
119 119 def create_default_config(self):
120 """Create defaults that can't be set elsewhere."""
120 """Create defaults that can't be set elsewhere.
121
122 For the most part, we try to set default in the class attributes
123 of Components. But, defaults the top-level Application (which is
124 not a HasTraitlets or Component) are not set in this way. Instead
125 we set them here. The Global section is for variables like this that
126 don't belong to a particular component.
127 """
121 128 self.default_config = Config()
122 129 self.default_config.Global.ipythondir = get_ipython_dir()
123 130 self.log.debug('Default config loaded:')
@@ -139,6 +146,7 b' class Application(object):'
139 146
140 147 loader = self.create_command_line_config()
141 148 self.command_line_config = loader.load_config()
149 self.extra_args = loader.get_extra_args()
142 150
143 151 try:
144 152 self.log_level = self.command_line_config.Global.log_level
@@ -104,11 +104,6 b' cl_args = ('
104 104 action='store_false', dest='Global.display_banner', default=NoConfigDefault,
105 105 help="Don't display a banner upon starting IPython.")
106 106 ),
107 (('-c',), dict(
108 type=str, dest='InteractiveShell.c', default=NoConfigDefault,
109 help="Execute the given command string.",
110 metavar='InteractiveShell.c')
111 ),
112 107 (('-cache_size',), dict(
113 108 type=int, dest='InteractiveShell.cache_size', default=NoConfigDefault,
114 109 help="Set the size of the output cache.",
@@ -251,6 +246,15 b' cl_args = ('
251 246 help="The dotted module name of an IPython extension to load.",
252 247 metavar='Global.extra_extension')
253 248 ),
249 (('-c',), dict(
250 type=str, dest='Global.code_to_run', default=NoConfigDefault,
251 help="Execute the given command string.",
252 metavar='Global.code_to_run')
253 ),
254 (('-i',), dict(
255 action='store_true', dest='Global.force_interact', default=NoConfigDefault,
256 help="If running code from the command line, become interactive afterwards.")
257 ),
254 258 # These are only here to get the proper deprecation warnings
255 259 (('-pylab','-wthread','-qthread','-q4thread','-gthread'), dict(
256 260 action='store_true', dest='Global.threaded_shell', default=NoConfigDefault,
@@ -272,7 +276,16 b' class IPythonApp(Application):'
272 276
273 277 def create_default_config(self):
274 278 super(IPythonApp, self).create_default_config()
275 self.default_config.Global.display_banner=True
279 self.default_config.Global.display_banner = True
280
281 # If the -c flag is given or a file is given to run at the cmd line
282 # like "ipython foo.py", normally we exit without starting the main
283 # loop. The force_interact config variable allows a user to override
284 # this and interact. It is also set by the -i cmd line flag, just
285 # like Python.
286 self.default_config.Global.force_interact = False
287 # By default always interact by starting the IPython mainloop.
288 self.default_config.Global.interact = True
276 289 # Let the parent class set the default, but each time log_level
277 290 # changes from config, we need to update self.log_level as that is
278 291 # what updates the actual log level in self.log.
@@ -324,15 +337,22 b' class IPythonApp(Application):'
324 337 config.InteractiveShell.colors = 'NoColor'
325 338 config.InteractiveShell.xmode = 'Plain'
326 339
327 # All this should be moved to traitlet handlers in InteractiveShell
328 # But, currently InteractiveShell doesn't have support for changing
329 # these values at runtime. Once we support that, this should
330 # be moved there!!!
331 340 if hasattr(config.Global, 'nosep'):
332 341 if config.Global.nosep:
333 342 config.InteractiveShell.separate_in = \
334 343 config.InteractiveShell.separate_out = \
335 config.InteractiveShell.separate_out2 = '0'
344 config.InteractiveShell.separate_out2 = ''
345
346 # if there is code of files to run from the cmd line, don't interact
347 # unless the -i flag (Global.force_interact) is true.
348 code_to_run = config.Global.get('code_to_run','')
349 file_to_run = False
350 if len(self.extra_args)>=1:
351 if self.extra_args[0]:
352 file_to_run = True
353 if file_to_run or code_to_run:
354 if not config.Global.force_interact:
355 config.Global.interact = False
336 356
337 357 def construct(self):
338 358 # I am a little hesitant to put these into InteractiveShell itself.
@@ -352,7 +372,8 b' class IPythonApp(Application):'
352 372 # so the banner shows *before* all extension loading stuff.
353 373 self.shell.display_banner = False
354 374
355 if self.master_config.Global.display_banner:
375 if self.master_config.Global.display_banner and \
376 self.master_config.Global.interact:
356 377 self.shell.show_banner()
357 378
358 379 # Make sure there is a space below the banner.
@@ -361,6 +382,7 b' class IPythonApp(Application):'
361 382 self._load_extensions()
362 383 self._run_exec_lines()
363 384 self._run_exec_files()
385 self._run_cmd_line_code()
364 386
365 387 def _load_extensions(self):
366 388 """Load all IPython extensions in Global.extensions.
@@ -400,29 +422,55 b' class IPythonApp(Application):'
400 422 self.log.warn("Unknown error in handling Global.exec_lines:")
401 423 self.shell.showtraceback()
402 424
425 def _exec_file(self, fname):
426 full_filename = filefind(fname, ['.', self.ipythondir])
427 if os.path.isfile(full_filename):
428 if full_filename.endswith('.py'):
429 self.log.info("Running file in user namespace: %s" % full_filename)
430 self.shell.safe_execfile(full_filename, self.shell.user_ns)
431 elif full_filename.endswith('.ipy'):
432 self.log.info("Running file in user namespace: %s" % full_filename)
433 self.shell.safe_execfile_ipy(full_filename)
434 else:
435 self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename)
436
403 437 def _run_exec_files(self):
404 438 try:
405 439 if hasattr(self.master_config.Global, 'exec_files'):
406 440 self.log.debug("Running files in Global.exec_files...")
407 441 exec_files = self.master_config.Global.exec_files
408 442 for fname in exec_files:
409 full_filename = filefind(fname, ['.', self.ipythondir])
410 if os.path.isfile(full_filename):
411 if full_filename.endswith('.py'):
412 self.log.info("Running file in user namespace: %s" % full_filename)
413 self.shell.safe_execfile(full_filename, self.shell.user_ns)
414 elif full_filename.endswith('.ipy'):
415 self.log.info("Running file in user namespace: %s" % full_filename)
416 self.shell.safe_execfile_ipy(full_filename)
417 else:
418 self.log.warn("File does not have a .py or .ipy extension: <%s>" % full_filename)
443 self._exec_file(fname)
419 444 except:
420 445 self.log.warn("Unknown error in handling Global.exec_files:")
421 446 self.shell.showtraceback()
422 447
448 def _run_cmd_line_code(self):
449 if hasattr(self.master_config.Global, 'code_to_run'):
450 line = self.master_config.Global.code_to_run
451 try:
452 self.log.info("Running code given at command line (-c): %s" % line)
453 self.shell.runlines(line)
454 except:
455 self.log.warn("Error in executing line in user namespace: %s" % line)
456 self.shell.showtraceback()
457 return
458 # Like Python itself, ignore the second if the first of these is present
459 try:
460 fname = self.extra_args[0]
461 except:
462 pass
463 else:
464 try:
465 self._exec_file(fname)
466 except:
467 self.log.warn("Error in executing file in user namespace: %s" % fname)
468 self.shell.showtraceback()
469
423 470 def start_app(self):
424 self.log.debug("Starting IPython's mainloop...")
425 self.shell.mainloop()
471 if self.master_config.Global.interact:
472 self.log.debug("Starting IPython's mainloop...")
473 self.shell.mainloop()
426 474
427 475
428 476 def load_default_config(ipythondir=None):
@@ -189,7 +189,6 b' class InteractiveShell(Component, Magic):'
189 189 banner = Str('')
190 190 banner1 = Str(default_banner, config=True)
191 191 banner2 = Str('', config=True)
192 c = Str('', config=True)
193 192 cache_size = Int(1000, config=True)
194 193 color_info = CBool(True, config=True)
195 194 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
@@ -207,7 +206,6 b' class InteractiveShell(Component, Magic):'
207 206 embedded_active = CBool(False)
208 207 editor = Str(get_default_editor(), config=True)
209 208 filename = Str("<ipython console>")
210 interactive = CBool(False, config=True)
211 209 ipythondir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
212 210 logstart = CBool(False, config=True)
213 211 logfile = Str('', config=True)
@@ -1702,8 +1700,6 b' class InteractiveShell(Component, Magic):'
1702 1700 """
1703 1701
1704 1702 with nested(self.builtin_trap, self.display_trap):
1705 if self.c: # Emulate Python's -c option
1706 self.exec_init_cmd()
1707 1703
1708 1704 # if you run stuff with -c <cmd>, raw hist is not updated
1709 1705 # ensure that it's in sync
@@ -1722,16 +1718,6 b' class InteractiveShell(Component, Magic):'
1722 1718 # handling seems rather unpredictable...
1723 1719 self.write("\nKeyboardInterrupt in interact()\n")
1724 1720
1725 def exec_init_cmd(self):
1726 """Execute a command given at the command line.
1727
1728 This emulates Python's -c option."""
1729
1730 #sys.argv = ['-c']
1731 self.push_line(self.prefilter_manager.prefilter_lines(self.c, False))
1732 if not self.interactive:
1733 self.ask_exit()
1734
1735 1721 def interact_prompt(self):
1736 1722 """ Print the prompt (in read-eval-print loop)
1737 1723
@@ -2297,24 +2283,6 b' class InteractiveShell(Component, Magic):'
2297 2283 else:
2298 2284 return lineout
2299 2285
2300 # def init_exec_commands(self):
2301 # for cmd in self.config.EXECUTE:
2302 # print "execute:", cmd
2303 # self.api.runlines(cmd)
2304 #
2305 # batchrun = False
2306 # if self.config.has_key('EXECFILE'):
2307 # for batchfile in [path(arg) for arg in self.config.EXECFILE
2308 # if arg.lower().endswith('.ipy')]:
2309 # if not batchfile.isfile():
2310 # print "No such batch file:", batchfile
2311 # continue
2312 # self.api.runlines(batchfile.text())
2313 # batchrun = True
2314 # # without -i option, exit after running the batch file
2315 # if batchrun and not self.interactive:
2316 # self.ask_exit()
2317
2318 2286 #-------------------------------------------------------------------------
2319 2287 # IPython extensions
2320 2288 #-------------------------------------------------------------------------
General Comments 0
You need to be logged in to leave comments. Login now