Communities

Writing
Writing
Codidact Meta
Codidact Meta
The Great Outdoors
The Great Outdoors
Photography & Video
Photography & Video
Scientific Speculation
Scientific Speculation
Cooking
Cooking
Electrical Engineering
Electrical Engineering
Judaism
Judaism
Languages & Linguistics
Languages & Linguistics
Software Development
Software Development
Mathematics
Mathematics
Christianity
Christianity
Code Golf
Code Golf
Music
Music
Physics
Physics
Linux Systems
Linux Systems
Power Users
Power Users
Tabletop RPGs
Tabletop RPGs
Community Proposals
Community Proposals
tag:snake search within a tag
answers:0 unanswered questions
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
votes:4 posts with 4+ votes
created:<1w created < 1 week ago
post_type:xxxx type of post
Search help
Notifications
Mark all as read See all your notifications »
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

Comments on How and where does Python code start running? How can I control that?

Parent

How and where does Python code start running? How can I control that?

+6
−0

Suppose I have some code in a file myscript.py like:

def my_function():
    print("Test")

What steps do I need to take in order to make my_function run? That is to say: how do I get Python to run myscript.py; and from there, how do I choose my_function as the starting point for the code? In particular, do I need to use a specific name for my starting function (such as main, as seen in some other programming languages)?

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.
Why should this post be closed?

1 comment thread

Background and intended scope (2 comments)
Post
+5
−1

Starting up Python

There are several key ways to use the python command from the command line:

  • python by itself starts a REPL that allows typing in and running Python code on the fly, one statement at a time.

  • python myscript.py runs the code in myscript.py, assuming it's in the current directory. Python will not search for the file to run; the path needs to be given explicitly on the command line.

  • python -c "code here" treats the text supplied as a -c argument as Python code and runs it directly. (This example will report a SyntaxError, because code here is not valid Python code.)

  • python -m myscript tries to find a module named myscript and run it.

Finally, when using one of the latter three methods, it's also possible to pass the -i ("interactive") flag. This makes Python start up a REPL after running the other specified code, and any global variables from that code will be available in the interpreter.

Understanding the -m flag

Using python -m to run the code differs from giving a file name or path in several ways:

  • The supplied name needs to be a module path, the way it would look in an absolute import statement inside the code. Since we would import myscript.py (assuming everything else were set up properly) using something like import myscript (with no .py), that's how the command looks: python -m myscript (with no .py).

  • This changes the rules for where Python looks for modules. If for example we had myscript.py inside of myfolder, then python -m myfolder.myscript tell Python that *the current directory (.) is a place that may contain modules and packages. But python myfolder/myscript.py will tell Python that the myfolder directory is a place that may contain modules and packages.

  • Python will search for the named module, instead of following a specific file path. This is important because some standard library modules (and possibly some third-party packages) offer their own command-line interface, and can be run like scripts instead of just importing them from one's own code.

  • Starting the code this way will also import packages for folders along the way: python -m myfolder.myscript will make myfolder a package (and run code in myfolder/__init__.py, if there is such a file). This also allows relative imports to work.

Where code starts running

Background understanding

It's important to understand that from Python's perspective, running a script is not much different from importing a module. Either way, the code is run from top to bottom in the file. Any code that isn't indented happens immediately, in order. (Some code that is indented might still happen: for example, code inside an if block would run if the condition is satisfied.) This includes things like import statements, by the way: they aren't required to be at the top of the file (although this is usually a good idea), and they happen when Python encounters them, not automatically.

Keep in mind that this does not mean that functions are called: "running" the code in the question simply creates the function - it doesn't make the code inside the function run.

There are no "special" function names here. Python won't automatically call a function named main, or anything else - functions only run when they are called.

Sometimes, you may want to avoid having top-level code run - for example, because the file will be both run as a script, and imported from somewhere else. In this case you can use the if __name__ == '__main__': idiom.

Strategies for calling my_function

Therefore, in order for my_function to run in the example code, there has to be a call like my_function() somewhere. There are a few ways to make this happen:

  • Start the interpreter like python; then use the REPL to import myscript and call myscript.my_function(). (Or similar ideas, like using from myscript import my_function and then my_function().)

  • Use python -c to specify similar code: python -c "import myscript; myscript.my_function()".

  • Add code like my_function() "at top level", so that it runs immediately, and calls the function. Keep in mind that the function has to appear first in the file - otherwise, Python won't have created it yet, so it can't be called.

The last way is the normal way for whatever we consider a "script", i.e. something we want to run directly. That's because otherwise we have to rely on importing the code, which has a different meaning from what we're trying to express. Letting the script call the function itself is also more "automatic"; the user doesn't have to take a second step to use the code, and doesn't have to know what the function is called.

Of course, it's also possible to just put a bunch of un-indented code in myscript.py, and not bother with a function. However, keeping the main part of the code inside a function will be better in the long run for organizational purposes.

History
Why does this post require attention from curators or moderators?
You might want to add some details to your flag.

1 comment thread

Split up answer (7 comments)
Split up answer

Making scripts run themselves

This entire section should be moved elsewhere.

The question is an introductory at Python, and a nice place to start learning for a beginner, but for anybody searching for how to do what this section describes, this question is a bad fit. You should make a new Q/A, move this section there, and link to it from the end of this answer.

Keep this only for how Python works; omit further explanations in this location.

When splitting, you risk running into another issue: a question for how to make Python scripts into (native) executables/applications for all platforms. That's too much at once. One question per platform. Maybe there's a space for having an overview of all of them. Maybe dedicate a Q/A to asking about all platforms, then having an answer listing links to more specific Q/As?

Karl Knechtel‭ wrote 8 months ago

I agree, at least superficially. When I started writing I had it in mind that "running" the script as an executable is the same sort of thing as invoking Python to run it (since it's still asking a Python runtime to evaluate the code, just the other way around). But looking at it now - especially given the question phrasing, which was really the only way I could make it make sense - this section seems bolted on now.

I think that "creating standalone executables" is a coherent task description and it doesn't really matter whether the executable is an OS-privileged script, a bundled script+runtime environment or something which is somehow natively compiled. Those are all solutions for the same fundamental task, and could stand as separate As on the same Q.

I'm also generally opposed to making platform-specific versions of Q&A for things that can be done on all platforms. That just makes it harder to deal with platform-agnostic answers.

Andreas witnessed the end of the world today‭ wrote 8 months ago · edited 8 months ago

But creating a standalone executable is also different for each system. If I'm looking to make my Python application executable on my Mac without having to jump into the IDE to click the "run" button, I'm not interested in how to do it on Windows, Linux, etc, and I'd rather not have to scroll past that, and search within a long text for just how to do it in MacOS.

I'm also generally opposed to making platform-specific versions of Q&A for things that can be done on all platforms. That just makes it harder to deal with platform-agnostic answers.

I agree there should be an overview, as one of the things that's been bothering me on SO, is that it's hard to see the proper scope of things, or find related stuff. However, if we'd have to choose between one or the other, I'd still pick the smaller, focused Q/As. They are easier to navigate, and far more specific, which is great when I need an answer to my problem, and when searching online. One of the things I dislike the most, is having to scroll past irrelevant content to find what I need.

Sometimes I do want that long overview, though, but generally not. It's also not so useful when actually using the Q/A to help implement something in the codebase. It's too big and unfocused.

Karl Knechtel‭ wrote 6 months ago

I guess you're aware, but I've split away content from this answer according to my plan now. If the downvote was yours, please feel free to re-evaluate.

Nope, not mine. :)