[Tutor] Calling another script
Steven D'Aprano
steve at pearwood.info
Mon Apr 4 10:46:01 CEST 2011
On Mon, Apr 04, 2011 at 05:10:50AM +0000, tee chwee liong wrote:
>
> hi,
>
> i opened a cmd DOS prompt to execute one.py. it works to execute codes from two.py and three.py. yes, you are fight it will not re-execute the module.
> is there a way to do it? i want after the python script finishes execution will return the control to the DOS prompt instead of leaving as >>>.
> i tried putting sys.exit().
Do not confuse importing a script with running a script.
The usual way to run a script is to write it with a main() function, and then call that:
# === myscript.py ===
print("Set up code goes here...")
# this only gets executed once, the FIRST time you import the module
def main():
print("Running script now!")
if __name__ == '__main__':
# We've been called from the shell.
main()
In your other script, you do this:
# === Master script that calls myscript ===
if __name__ == '__main__':
# Running as a script ourselves.
import myscript
myscript.main()
--
Steven
More information about the Tutor
mailing list