Ask Your Question
0

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

asked 2017-07-02 16:44:02 +0100

jaebond gravatar image

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

def func()
    print('Hello!')

if __name__ == '__main__':
    func()

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

sage: load('module.sage')
Hello!
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
1

answered 2017-07-13 23:35:09 +0100

vdelecroix gravatar image

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

def func()
    print('Hello!')

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

(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

Stats

Asked: 2017-07-02 16:44:02 +0100

Seen: 748 times

Last updated: Jul 13 '17