As mentioned in the comments, if you're working in a terminal you should use the command (remember to do this from the main shell, ie probably bash, not from the Python shell)
$ python script.py
This is the intended way to execute python files. You can normally quickly cycle back to the previous command with the UP arrow on your keyboard.
However, if you for some reason really need to run your script from the interactive interpreter, there are some options, although beware that they are kind of hacky and probably not the best way to go about running your code, although this may vary with what your specific use case is.
If your script, hello.py
, had the following source:
print("hello world")
In python3 you could do the following from the shell:
>>> from importlib import reload
>>> import hello
hello world
>>> reload(hello)
hello world
<module 'hello' from '/home/izaak/programmeren/stackoverflow/replrun/hello.py'>
Here is the documentation for importlib.reload
. As you can see, this replicates the side effects of the script. The second part is the repr()
of the module, as the reload()
function returns the module - this is nothing to worry about, it is part of the way the interpreter works, in that it prints the value of anything you enter into it - eg you can do
>>> 2 + 3
5
rather than having to explicitly print(2 + 3)
. If this really bother you, you could do
>>> from importlib import reload as _reload
>>> def reload(mod):
... _reload(mod)
...
>>> import hello
hello world
>>> reload(hello)
hello world
However, it would be more idiomatic for your script to look something like this, using that if
statement you found (this was also a suggestion in the comments):
def main():
print("hello world")
if __name__ == "__main__":
main()
This way, from the Python shell you can do:
>>> import hello
>>> hello.main()
hello world
>>> hello.main()
hello world
This is very good practice. The if
statement here checks if the script is being executed as the 'main' script (like running it directly from the command line, as in my first suggestion), and if so it executes the main function. This means that the script will not do anything if another script wants to import
it, allowing it to act more like a module.
If you're using IPython, you'll probably know this but this becomes a lot easier and you can do
In [1]: %run hello.py
hello world