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.
How and where does Python code start running? How can I control that?
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)?
2 answers
The following users marked this post as Works for me:
User | Comment | Date |
---|---|---|
Karl Knechtel | (no comment) | Apr 21, 2024 at 00:37 |
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 inmyscript.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 aSyntaxError
, becausecode here
is not valid Python code.) -
python -m myscript
tries to find a module namedmyscript
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:
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 importmyscript.py
(assuming everything else were set up properly) using something likeimport 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 ofmyfolder
, thenpython -m myfolder.myscript
tell Python that *the current directory (.
) is a place that may contain modules and packages. Butpython myfolder/myscript.py
will tell Python that themyfolder
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 makemyfolder
a package (and run code inmyfolder/__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 import
ed 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 toimport myscript
and callmyscript.my_function()
. (Or similar ideas, like usingfrom myscript import my_function
and thenmy_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 import
ing 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.
Files with .py
extension are scripts. You run them with python myscript.py
.
Python is an imperative language, so executing a file will run each line one by one, starting from the top, and exit when the end of the file is reached.
In your example, the script is saying:
- Create a function called
my_function
. - This function, when called, will print some text.
Notice we're telling Python to create the function, but we never tell it to call that function. Your example will appear to do nothing when executed. (Well, it may briefly waste some memory to store this function, which never gets used.)
You have two options here: either get rid of the function definition, or add a call to execute it.
Option 1:
# an actual command, not the content of a function definition
print("Test")
Option 2:
# define a function
def my_function():
print("Test")
# actually execute the function
my_function()
1 comment thread