Ask Your Question
0

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

asked 7 years ago

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.

Preview: (hide)

1 Answer

Sort by » oldest newest most voted
1

answered 7 years ago

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)

Preview: (hide)
link

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: 7 years ago

Seen: 996 times

Last updated: Jul 13 '17