Skip to main content

Timeline for Python exec and __name__

Current License: CC BY-SA 4.0

13 events
when toggle format what by license comment
Jan 19, 2022 at 19:24 comment added Martijn Pieters @mkrieger1: you could have tried it? It's still applicable to Python 3. I've updated the syntax here and in the question to use Python 3 compatible exec() and print() calls.
Jan 19, 2022 at 19:22 history edited Martijn Pieters CC BY-SA 4.0
Update to use Python 3 compatible syntax
Dec 14, 2021 at 17:55 comment added mkrieger1 Is this answer still valid for Python 3, or what needs to be updated? (or where is the appropriate existing Q&A for Python 3?)
Apr 1, 2013 at 14:18 vote accept Tuom L.
Apr 1, 2013 at 14:00 comment added Martijn Pieters 'here' as in your question. __name__ is a module global, in modules globals and locals are the same thing so you should not supply a locals mapping. Testing for __name__ is the defacto way to test if this is the main script, setting it is enough.
Apr 1, 2013 at 13:54 comment added Tuom L. One last question, the docs say exec expr in globals, locals - should I put {'__name__':'__main__'} in globals or locals? exec src in {'__name__':'__main__'} or exec src in {}, {'__name__':'__main__'}
Apr 1, 2013 at 13:27 comment added Tuom L. I'm sorry I don't understand your last comment - what do you mean by "here"? The src string? And I have to ask similar question as for the other answer - is in {'__name__':'__main__'} enough to make src believe it was executed from command line? I mean are there any traps I should know about? If it is enough though that would make it for a perfect solution, thanks in any case...
Apr 1, 2013 at 11:04 history edited Martijn Pieters CC BY-SA 3.0
added 308 characters in body
Apr 1, 2013 at 11:04 comment added Martijn Pieters Note that the expectation that __name__ == '__main__' works implies you are executing modules here.
Apr 1, 2013 at 10:12 comment added Martijn Pieters In order to import a module, it has to be executed.
Apr 1, 2013 at 10:05 comment added Tuom L. I cannot unfortunately create a temporary file on disk. Isn't there a way to execute plain string as if it was run from command line? And one more question about your reply: it looks like it as if it was importing (as in import) the file - does it import or execute the file? Is there a difference?
Apr 1, 2013 at 9:51 history edited Martijn Pieters CC BY-SA 3.0
added 203 characters in body
Apr 1, 2013 at 9:39 history answered Martijn Pieters CC BY-SA 3.0