OptionParser on ipython laptop?

I like to develop ipython inside the laptop, but I got a problem when I want to write a main () function that reads command line arguments (e.g. using OptionParser). I want to be able to export the code to a .py file and run it from the command line, but I have not found a way to have main (), which works both on a laptop with predefined arguments, and from the command line with python and command line arguments. What's the secret?

If this is not clear, I would like to do something like this:

if __name__ == '__main__': # if in the notebook vals = {'debug':True, 'tag_file': 't.tags'} options = Object() for k,v in vals.items(): options.setattr(k,v) args = 'fname1.txt' # if running as a command line python script from optparse import OptionParser parser = OptionParser() parser.add_option('-d','--debug',action='store_true',dest='debug') parser.add_option('-t','--tags',action='store',dest='tag_file') options,args = parser.parse_args() 
+1
ipython-notebook
source share
2 answers

You cannot determine if you are in an IPython laptop or qtconsole or in a simple IPython shell, for the simple reason that 3 can be connected to the same kernel at the same time.

It will be like asking what color is the current key that the user enters. You can get it by looking at the connected USB devices and look at the images on the Internet and guess the color of the keyboard, but nothing guarantees that it will be accurate and that it will not change, and the user can connect several keyboards or even a painted keyboard.

This is really the same with a notebook. Even if you determine that you are in ZMQKernel, are you browsing qtconsole or a web server? Again, you find yourself talking to a web server, are you talking to JS or Emacs? And so on and so forth.

The only thing you can do is ask the user.

What is reliable is the test that you use in IPython or not.


If you really , but reeaaalllyy want a way, since still a laptop is the only thing that Javascript can display. And javascript can execute code in pyton. That way, you could be able to create something that displays JSs that send information back to the kernel. And using a thread and a timer, you can say that you were not in the laptop (but you will have a race condition).

+1
source share

Do not worry about the difference. Just set the defaults, and if they are not overridden from the command line, use them.

 if __name__ == '__main__': parser = OptionParser() parser.add_option('-d', '--debug', action='store_true', dest='debug', default=True) parser.add_option('-t','--tags',action='store',dest='tag_file', default='t.tags') options, args = parser.parse_args() if not args: args = ['fname1.txt'] 
0
source share

All Articles