##// END OF EJS Templates
disallow no-prefix `ipython foo=bar` argument style....
MinRK -
r4197:368e365a
parent child
Show More
@@ -325,15 +325,15 class CommandLineConfigLoader(ConfigLoader):
325 325 here.
326 326 """
327 327
328 kv_pattern = re.compile(r'[A-Za-z]\w*(\.\w+)*\=.*')
329 flag_pattern = re.compile(r'\w+(\-\w)*')
328 kv_pattern = re.compile(r'\-\-[A-Za-z]\w*(\.\w+)*\=.*')
329 flag_pattern = re.compile(r'\-\-?\w+[\-\w]*$')
330 330
331 331 class KeyValueConfigLoader(CommandLineConfigLoader):
332 332 """A config loader that loads key value pairs from the command line.
333 333
334 334 This allows command line options to be gives in the following form::
335 335
336 ipython Global.profile="foo" InteractiveShell.autocall=False
336 ipython --profile="foo" --InteractiveShell.autocall=False
337 337 """
338 338
339 339 def __init__(self, argv=None, aliases=None, flags=None):
@@ -364,7 +364,7 class KeyValueConfigLoader(CommandLineConfigLoader):
364 364
365 365 >>> from IPython.config.loader import KeyValueConfigLoader
366 366 >>> cl = KeyValueConfigLoader()
367 >>> cl.load_config(["foo='bar'","A.name='brian'","B.number=0"])
367 >>> cl.load_config(["--foo='bar'","--A.name='brian'","--B.number=0"])
368 368 {'A': {'name': 'brian'}, 'B': {'number': 0}, 'foo': 'bar'}
369 369 """
370 370 self.clear()
@@ -437,7 +437,7 class KeyValueConfigLoader(CommandLineConfigLoader):
437 437 self.extra_args.extend(uargv[idx+1:])
438 438 break
439 439
440 if kv_pattern.match(item):
440 if kv_pattern.match(raw):
441 441 lhs,rhs = item.split('=',1)
442 442 # Substitute longnames for aliases.
443 443 if lhs in aliases:
@@ -455,17 +455,24 class KeyValueConfigLoader(CommandLineConfigLoader):
455 455 # it succeeds. If it still fails, we let it raise.
456 456 exec_str = u'self.config.' + lhs + '=' + repr(rhs)
457 457 exec exec_str in locals(), globals()
458 elif item in flags:
459 cfg,help = flags[item]
460 if isinstance(cfg, (dict, Config)):
461 # don't clobber whole config sections, update
462 # each section from config:
463 for sec,c in cfg.iteritems():
464 self.config[sec].update(c)
458 elif flag_pattern.match(raw):
459 if item in flags:
460 cfg,help = flags[item]
461 if isinstance(cfg, (dict, Config)):
462 # don't clobber whole config sections, update
463 # each section from config:
464 for sec,c in cfg.iteritems():
465 self.config[sec].update(c)
466 else:
467 raise ValueError("Invalid flag: '%s'"%raw)
465 468 else:
466 raise ValueError("Invalid flag: '%s'"%raw)
469 raise ArgumentError("Unrecognized flag: '%s'"%raw)
467 470 elif raw.startswith('-'):
468 raise ArgumentError("invalid argument: '%s'"%raw)
471 kv = '--'+item
472 if kv_pattern.match(kv):
473 raise ArgumentError("Invalid argument: '%s', did you mean '%s'?"%(raw, kv))
474 else:
475 raise ArgumentError("Invalid argument: '%s'"%raw)
469 476 else:
470 477 # keep all args that aren't valid in a list,
471 478 # in case our parent knows what to do with them.
@@ -79,7 +79,7 class TestApplication(TestCase):
79 79
80 80 def test_config(self):
81 81 app = MyApp()
82 app.parse_command_line(["--i=10","Foo.j=10","--enabled=False","-log_level=50"])
82 app.parse_command_line(["--i=10","--Foo.j=10","--enabled=False","--log_level=50"])
83 83 config = app.config
84 84 self.assertEquals(config.Foo.i, 10)
85 85 self.assertEquals(config.Foo.j, 10)
@@ -88,7 +88,7 class TestApplication(TestCase):
88 88
89 89 def test_config_propagation(self):
90 90 app = MyApp()
91 app.parse_command_line(["i=10","--Foo.j=10","enabled=False","log_level=50"])
91 app.parse_command_line(["--i=10","--Foo.j=10","--enabled=False","--log_level=50"])
92 92 app.init_foo()
93 93 app.init_bar()
94 94 self.assertEquals(app.foo.i, 10)
@@ -97,7 +97,7 class TestApplication(TestCase):
97 97
98 98 def test_flags(self):
99 99 app = MyApp()
100 app.parse_command_line(["-disable"])
100 app.parse_command_line(["--disable"])
101 101 app.init_bar()
102 102 self.assertEquals(app.bar.enabled, False)
103 103 app.parse_command_line(["--enable"])
@@ -106,7 +106,7 class TestApplication(TestCase):
106 106
107 107 def test_aliases(self):
108 108 app = MyApp()
109 app.parse_command_line(["i=5", "j=10"])
109 app.parse_command_line(["--i=5", "--j=10"])
110 110 app.init_foo()
111 111 self.assertEquals(app.foo.i, 5)
112 112 app.init_foo()
@@ -115,18 +115,18 class TestApplication(TestCase):
115 115 def test_flag_clobber(self):
116 116 """test that setting flags doesn't clobber existing settings"""
117 117 app = MyApp()
118 app.parse_command_line(["Bar.b=5", "--disable"])
118 app.parse_command_line(["--Bar.b=5", "--disable"])
119 119 app.init_bar()
120 120 self.assertEquals(app.bar.enabled, False)
121 121 self.assertEquals(app.bar.b, 5)
122 app.parse_command_line(["--enable", "Bar.b=10"])
122 app.parse_command_line(["--enable", "--Bar.b=10"])
123 123 app.init_bar()
124 124 self.assertEquals(app.bar.enabled, True)
125 125 self.assertEquals(app.bar.b, 10)
126 126
127 127 def test_extra_args(self):
128 128 app = MyApp()
129 app.parse_command_line(["Bar.b=5", 'extra', "--disable", 'args'])
129 app.parse_command_line(["--Bar.b=5", 'extra', "--disable", 'args'])
130 130 app.init_bar()
131 131 self.assertEquals(app.bar.enabled, True)
132 132 self.assertEquals(app.bar.b, 5)
@@ -119,7 +119,7 class TestKeyValueCL(TestCase):
119 119
120 120 def test_basic(self):
121 121 cl = KeyValueConfigLoader()
122 argv = [s.strip('c.') for s in pyfile.split('\n')[2:-1]]
122 argv = ['--'+s.strip('c.') for s in pyfile.split('\n')[2:-1]]
123 123 config = cl.load_config(argv)
124 124 self.assertEquals(config.a, 10)
125 125 self.assertEquals(config.b, 20)
@@ -129,21 +129,21 class TestKeyValueCL(TestCase):
129 129
130 130 def test_extra_args(self):
131 131 cl = KeyValueConfigLoader()
132 config = cl.load_config(['a=5', 'b', 'c=10', 'd'])
133 self.assertEquals(cl.extra_args, ['b', 'c=10' , 'd'])
132 config = cl.load_config(['--a=5', 'b', '--c=10', 'd'])
133 self.assertEquals(cl.extra_args, ['b', '--c=10' , 'd'])
134 134 self.assertEquals(config.a, 5)
135 135 self.assertRaises(AttributeError, getattr, config, 'c')
136 config = cl.load_config(['--', 'a=5', 'c=10'])
137 self.assertEquals(cl.extra_args, ['a=5', 'c=10'])
136 config = cl.load_config(['--', '--a=5', '--c=10'])
137 self.assertEquals(cl.extra_args, ['--a=5', '--c=10'])
138 138
139 139 def test_unicode_args(self):
140 140 cl = KeyValueConfigLoader()
141 argv = [u'a=épsîlön']
141 argv = [u'--a=épsîlön']
142 142 config = cl.load_config(argv)
143 143 self.assertEquals(config.a, u'épsîlön')
144 144
145 145 def test_unicode_bytes_args(self):
146 uarg = u'a=é'
146 uarg = u'--a=é'
147 147 try:
148 148 barg = uarg.encode(sys.stdin.encoding)
149 149 except (TypeError, UnicodeEncodeError):
@@ -293,10 +293,10 class IPythonQtConsoleApp(BaseIPythonApplication):
293 293
294 294 self.kernel_argv = list(argv) # copy
295 295 # kernel should inherit default config file from frontend
296 self.kernel_argv.append("KernelApp.parent_appname='%s'"%self.name)
296 self.kernel_argv.append("--KernelApp.parent_appname='%s'"%self.name)
297 297 # scrub frontend-specific flags
298 298 for a in argv:
299 if a.startswith('--') and a[2:] in qt_flags:
299 if a.startswith('-') and a.lstrip('-') in qt_flags:
300 300 self.kernel_argv.remove(a)
301 301
302 302 def init_kernel_manager(self):
@@ -146,7 +146,8 flags['quick']=(
146 146
147 147 flags['i'] = (
148 148 {'TerminalIPythonApp' : {'force_interact' : True}},
149 "If running code from the command line, become interactive afterwards."
149 """also works as '-i'
150 If running code from the command line, become interactive afterwards."""
150 151 )
151 152 flags['pylab'] = (
152 153 {'TerminalIPythonApp' : {'pylab' : 'auto'}},
@@ -304,7 +304,7 class IPythonRunner(InteractiveRunner):
304 304 def __init__(self,program = 'ipython',args=None,out=sys.stdout,echo=True):
305 305 """New runner, optionally passing the ipython command to use."""
306 306
307 args0 = ['colors=NoColor',
307 args0 = ['--colors=NoColor',
308 308 '--no-term-title',
309 309 '--no-autoindent']
310 310 if args is None: args = args0
@@ -323,7 +323,7 class LocalControllerLauncher(LocalProcessLauncher):
323 323 controller_cmd = List(ipcontroller_cmd_argv, config=True,
324 324 help="""Popen command to launch ipcontroller.""")
325 325 # Command line arguments to ipcontroller.
326 controller_args = List(['--log-to-file','log_level=%i'%logging.INFO], config=True,
326 controller_args = List(['--log-to-file','--log_level=%i'%logging.INFO], config=True,
327 327 help="""command-line args to pass to ipcontroller""")
328 328
329 329 def find_args(self):
@@ -331,7 +331,7 class LocalControllerLauncher(LocalProcessLauncher):
331 331
332 332 def start(self, profile_dir):
333 333 """Start the controller by profile_dir."""
334 self.controller_args.extend(['profile_dir=%s'%profile_dir])
334 self.controller_args.extend(['--profile_dir=%s'%profile_dir])
335 335 self.profile_dir = unicode(profile_dir)
336 336 self.log.info("Starting LocalControllerLauncher: %r" % self.args)
337 337 return super(LocalControllerLauncher, self).start()
@@ -343,7 +343,7 class LocalEngineLauncher(LocalProcessLauncher):
343 343 engine_cmd = List(ipengine_cmd_argv, config=True,
344 344 help="""command to launch the Engine.""")
345 345 # Command line arguments for ipengine.
346 engine_args = List(['--log-to-file','log_level=%i'%logging.INFO], config=True,
346 engine_args = List(['--log-to-file','--log_level=%i'%logging.INFO], config=True,
347 347 help="command-line arguments to pass to ipengine"
348 348 )
349 349
@@ -352,7 +352,7 class LocalEngineLauncher(LocalProcessLauncher):
352 352
353 353 def start(self, profile_dir):
354 354 """Start the engine by profile_dir."""
355 self.engine_args.extend(['profile_dir=%s'%profile_dir])
355 self.engine_args.extend(['--profile_dir=%s'%profile_dir])
356 356 self.profile_dir = unicode(profile_dir)
357 357 return super(LocalEngineLauncher, self).start()
358 358
@@ -362,7 +362,7 class LocalEngineSetLauncher(BaseLauncher):
362 362
363 363 # Command line arguments for ipengine.
364 364 engine_args = List(
365 ['--log-to-file','log_level=%i'%logging.INFO], config=True,
365 ['--log-to-file','--log_level=%i'%logging.INFO], config=True,
366 366 help="command-line arguments to pass to ipengine"
367 367 )
368 368 # launcher class
@@ -468,20 +468,20 class MPIExecControllerLauncher(MPIExecLauncher):
468 468 controller_cmd = List(ipcontroller_cmd_argv, config=True,
469 469 help="Popen command to launch the Contropper"
470 470 )
471 controller_args = List(['--log-to-file','log_level=%i'%logging.INFO], config=True,
471 controller_args = List(['--log-to-file','--log_level=%i'%logging.INFO], config=True,
472 472 help="Command line arguments to pass to ipcontroller."
473 473 )
474 474 n = Int(1)
475 475
476 476 def start(self, profile_dir):
477 477 """Start the controller by profile_dir."""
478 self.controller_args.extend(['profile_dir=%s'%profile_dir])
478 self.controller_args.extend(['--profile_dir=%s'%profile_dir])
479 479 self.profile_dir = unicode(profile_dir)
480 480 self.log.info("Starting MPIExecControllerLauncher: %r" % self.args)
481 481 return super(MPIExecControllerLauncher, self).start(1)
482 482
483 483 def find_args(self):
484 return self.mpi_cmd + ['-n', self.n] + self.mpi_args + \
484 return self.mpi_cmd + ['-n', str(self.n)] + self.mpi_args + \
485 485 self.controller_cmd + self.controller_args
486 486
487 487
@@ -491,14 +491,14 class MPIExecEngineSetLauncher(MPIExecLauncher):
491 491 help="Popen command for ipengine"
492 492 )
493 493 program_args = List(
494 ['--log-to-file','log_level=%i'%logging.INFO], config=True,
494 ['--log-to-file','--log_level=%i'%logging.INFO], config=True,
495 495 help="Command line arguments for ipengine."
496 496 )
497 497 n = Int(1)
498 498
499 499 def start(self, n, profile_dir):
500 500 """Start n engines by profile or profile_dir."""
501 self.program_args.extend(['profile_dir=%s'%profile_dir])
501 self.program_args.extend(['--profile_dir=%s'%profile_dir])
502 502 self.profile_dir = unicode(profile_dir)
503 503 self.n = n
504 504 self.log.info('Starting MPIExecEngineSetLauncher: %r' % self.args)
@@ -567,7 +567,7 class SSHControllerLauncher(SSHLauncher):
567 567
568 568 program = List(ipcontroller_cmd_argv, config=True,
569 569 help="remote ipcontroller command.")
570 program_args = List(['--reuse-files', '--log-to-file','log_level=%i'%logging.INFO], config=True,
570 program_args = List(['--reuse-files', '--log-to-file','--log_level=%i'%logging.INFO], config=True,
571 571 help="Command line arguments to ipcontroller.")
572 572
573 573
@@ -745,7 +745,7 class WindowsHPCControllerLauncher(WindowsHPCLauncher):
745 745
746 746 def start(self, profile_dir):
747 747 """Start the controller by profile_dir."""
748 self.extra_args = ['profile_dir=%s'%profile_dir]
748 self.extra_args = ['--profile_dir=%s'%profile_dir]
749 749 self.profile_dir = unicode(profile_dir)
750 750 return super(WindowsHPCControllerLauncher, self).start(1)
751 751
@@ -779,7 +779,7 class WindowsHPCEngineSetLauncher(WindowsHPCLauncher):
779 779
780 780 def start(self, n, profile_dir):
781 781 """Start the controller by profile_dir."""
782 self.extra_args = ['profile_dir=%s'%profile_dir]
782 self.extra_args = ['--profile_dir=%s'%profile_dir]
783 783 self.profile_dir = unicode(profile_dir)
784 784 return super(WindowsHPCEngineSetLauncher, self).start(n)
785 785
@@ -936,7 +936,7 class PBSControllerLauncher(PBSLauncher):
936 936 default_template= Unicode("""#!/bin/sh
937 937 #PBS -V
938 938 #PBS -N ipcontroller
939 %s --log-to-file profile_dir={profile_dir}
939 %s --log-to-file --profile_dir={profile_dir}
940 940 """%(' '.join(ipcontroller_cmd_argv)))
941 941
942 942 def start(self, profile_dir):
@@ -952,7 +952,7 class PBSEngineSetLauncher(PBSLauncher):
952 952 default_template= Unicode(u"""#!/bin/sh
953 953 #PBS -V
954 954 #PBS -N ipengine
955 %s profile_dir={profile_dir}
955 %s --profile_dir={profile_dir}
956 956 """%(' '.join(ipengine_cmd_argv)))
957 957
958 958 def start(self, n, profile_dir):
@@ -977,7 +977,7 class SGEControllerLauncher(SGELauncher):
977 977 default_template= Unicode(u"""#$ -V
978 978 #$ -S /bin/sh
979 979 #$ -N ipcontroller
980 %s --log-to-file profile_dir={profile_dir}
980 %s --log-to-file --profile_dir={profile_dir}
981 981 """%(' '.join(ipcontroller_cmd_argv)))
982 982
983 983 def start(self, profile_dir):
@@ -992,7 +992,7 class SGEEngineSetLauncher(SGELauncher):
992 992 default_template = Unicode("""#$ -V
993 993 #$ -S /bin/sh
994 994 #$ -N ipengine
995 %s profile_dir={profile_dir}
995 %s --profile_dir={profile_dir}
996 996 """%(' '.join(ipengine_cmd_argv)))
997 997
998 998 def start(self, n, profile_dir):
@@ -1012,14 +1012,14 class IPClusterLauncher(LocalProcessLauncher):
1012 1012 ipcluster_cmd = List(ipcluster_cmd_argv, config=True,
1013 1013 help="Popen command for ipcluster")
1014 1014 ipcluster_args = List(
1015 ['--clean-logs', '--log-to-file', 'log_level=%i'%logging.INFO], config=True,
1015 ['--clean-logs', '--log-to-file', '--log_level=%i'%logging.INFO], config=True,
1016 1016 help="Command line arguments to pass to ipcluster.")
1017 1017 ipcluster_subcommand = Unicode('start')
1018 1018 ipcluster_n = Int(2)
1019 1019
1020 1020 def find_args(self):
1021 return self.ipcluster_cmd + ['--'+self.ipcluster_subcommand] + \
1022 ['n=%i'%self.ipcluster_n] + self.ipcluster_args
1021 return self.ipcluster_cmd + [self.ipcluster_subcommand] + \
1022 ['--n=%i'%self.ipcluster_n] + self.ipcluster_args
1023 1023
1024 1024 def start(self):
1025 1025 self.log.info("Starting ipcluster: %r" % self.args)
@@ -55,7 +55,7 def setup():
55 55
56 56 cp = TestProcessLauncher()
57 57 cp.cmd_and_args = ipcontroller_cmd_argv + \
58 ['profile=iptest', 'log_level=50']
58 ['--profile=iptest', '--log_level=50']
59 59 cp.start()
60 60 launchers.append(cp)
61 61 tic = time.time()
@@ -74,7 +74,7 def add_engines(n=1, profile='iptest'):
74 74 eps = []
75 75 for i in range(n):
76 76 ep = TestProcessLauncher()
77 ep.cmd_and_args = ipengine_cmd_argv + ['profile=%s'%profile, 'log_level=50']
77 ep.cmd_and_args = ipengine_cmd_argv + ['--profile=%s'%profile, '--log_level=50']
78 78 ep.start()
79 79 launchers.append(ep)
80 80 eps.append(ep)
@@ -158,8 +158,8 def default_argv():
158 158
159 159 return ['--quick', # so no config file is loaded
160 160 # Other defaults to minimize side effects on stdout
161 'colors=NoColor', '--no-term-title','--no-banner',
162 'autocall=0']
161 '--colors=NoColor', '--no-term-title','--no-banner',
162 '--autocall=0']
163 163
164 164
165 165 def default_config():
@@ -197,9 +197,9 def ipexec(fname, options=None):
197 197
198 198 # For these subprocess calls, eliminate all prompt printing so we only see
199 199 # output from script execution
200 prompt_opts = [ 'InteractiveShell.prompt_in1=""',
201 'InteractiveShell.prompt_in2=""',
202 'InteractiveShell.prompt_out=""'
200 prompt_opts = [ '--InteractiveShell.prompt_in1=""',
201 '--InteractiveShell.prompt_in2=""',
202 '--InteractiveShell.prompt_out=""'
203 203 ]
204 204 cmdargs = ' '.join(default_argv() + prompt_opts + options)
205 205
@@ -83,19 +83,19 def base_launch_kernel(code, shell_port=0, iopub_port=0, stdin_port=0, hb_port=0
83 83 # Build the kernel launch command.
84 84 if executable is None:
85 85 executable = sys.executable
86 arguments = [ executable, '-c', code, 'shell=%i'%shell_port,
87 'iopub=%i'%iopub_port, 'stdin=%i'%stdin_port,
88 'hb=%i'%hb_port
86 arguments = [ executable, '-c', code, '--shell=%i'%shell_port,
87 '--iopub=%i'%iopub_port, '--stdin=%i'%stdin_port,
88 '--hb=%i'%hb_port
89 89 ]
90 90 if ip is not None:
91 arguments.append('ip=%s'%ip)
91 arguments.append('--ip=%s'%ip)
92 92 arguments.extend(extra_arguments)
93 93
94 94 # Spawn a kernel.
95 95 if sys.platform == 'win32':
96 96 # Create a Win32 event for interrupting the kernel.
97 97 interrupt_event = ParentPollerWindows.create_interrupt_event()
98 arguments += [ 'interrupt=%i'%interrupt_event ]
98 arguments += [ '--interrupt=%i'%interrupt_event ]
99 99
100 100 # If this process in running on pythonw, stdin, stdout, and stderr are
101 101 # invalid. Popen will fail unless they are suitably redirected. We don't
@@ -133,7 +133,7 def base_launch_kernel(code, shell_port=0, iopub_port=0, stdin_port=0, hb_port=0
133 133 handle = DuplicateHandle(pid, pid, pid, 0,
134 134 True, # Inheritable by new processes.
135 135 DUPLICATE_SAME_ACCESS)
136 proc = Popen(arguments + ['parent=%i'%int(handle)],
136 proc = Popen(arguments + ['--parent=%i'%int(handle)],
137 137 stdin=_stdin, stdout=_stdout, stderr=_stderr)
138 138
139 139 # Attach the interrupt event to the Popen objet so it can be used later.
@@ -153,7 +153,6 def base_launch_kernel(code, shell_port=0, iopub_port=0, stdin_port=0, hb_port=0
153 153 proc = Popen(arguments, preexec_fn=lambda: os.setsid(),
154 154 stdin=stdin, stdout=stdout, stderr=stderr)
155 155 else:
156 proc = Popen(arguments + ['parent=1'],
156 proc = Popen(arguments + ['--parent=1'],
157 157 stdin=stdin, stdout=stdout, stderr=stderr)
158
159 158 return proc, shell_port, iopub_port, stdin_port, hb_port
@@ -166,7 +166,7 class KernelApp(BaseIPythonApplication):
166 166 # single-port connection negotiation fully implemented.
167 167 # set log-level to critical, to make sure it is output
168 168 self.log.critical("To connect another client to this kernel, use:")
169 self.log.critical("--existing shell={0} iopub={1} stdin={2} hb={3}".format(
169 self.log.critical("--existing --shell={0} --iopub={1} --stdin={2} --hb={3}".format(
170 170 self.shell_port, self.iopub_port, self.stdin_port, self.hb_port))
171 171
172 172
General Comments 0
You need to be logged in to leave comments. Login now