ryantuck
ryantuck

Reputation: 6644

Python - can't run same script twice in terminal when using import

I have a python script test.py I'm working on. I'd like to make edits and re-run it. I'm using Terminal on OSX to run the script. I can't get the script to run a second time without quitting out of terminal and starting it again.

# test.py
print "Howdy"

Terminal window:

$ python
>>> import test
Howdy
>>> import test
>>>

Question 1: How do I get the script to run again?

Question 2: Or is python designed to work like this:

# test.py
def printStuff():
    print "Howdy"

Terminal:

$ python
>>> import test
>>> test.printStuff()
Howdy
>>> test.printStuff()
Howdy
>>> 

Upvotes: 0

Views: 2037

Answers (3)

Mike Bell
Mike Bell

Reputation: 1386

1: you can use reload(moduleName) to do what you're trying to do (but see below).

2: There's a few different patterns, but I typically have a main() function inside all of my modules that have a clear "start point", or else I'll just have a bunch of library functions. So more or less what you're thinking in your example. You're not really supposed to "do stuff" on import, unless it's setting up the module. Think of a module as a library, not a script.

If you want to execute it as a script (in which case you shouldn't be using import), then there's a couple options. You can use a shebang at the top of your python script (Should I put #! (shebang) in Python scripts, and what form should it take?) and execute it directly from the command line, or you can use the __main__ module in your script as an entry point (https://docs.python.org/2/library/main.html), and then call the script with python from the command line, e.g. python myscript.

Upvotes: 3

Andy
Andy

Reputation: 50560

You want to use the reload method

>>> import test
Howdy
>>> reload(test)
Howdy

Upvotes: 1

Mike Driscoll
Mike Driscoll

Reputation: 33071

Use Python's reload() method:

Upvotes: 1

Related Questions