Ask Your Question

Loading a module causes the __name__ == '__main__' block to execute

asked 2017-07-02 09:44:02 -0500

jaebond gravatar image

I have a module that can also be run from the command line:

def func()

if __name__ == '__main__':

When I try to load it in Sage, the main block is executed:

sage: load('module.sage')

The bigger problem is that the main block parses command line arguments and Sage aborts the load with an error because it didn't receive any command line arguments. Is there any way to handle this? I can preparse module.sage and import it as a Python module, but its so much easier to attach('module.sage') than having to reload(module) every time I change it when I'm editing.

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2017-07-13 16:35:09 -0500

Note that the Sage console is using IPython. This question on stack overflow leads to the following trick

def func()

if __name__ == '__main__' and '__file__' in globals():

(does work for me with both %runfile and %attach)

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2017-07-02 09:44:02 -0500

Seen: 47 times

Last updated: Jul 13