Reputation: 133
I use a piece of astrophysical software called AMUSE, which uses python command line. I have got the binary release that imports amuse in terminal. Now if I want to run a saved python program in any directory, how do I call it?
Previously I used in terminal
python first.py
pwd=secret;database=master;uid=sa;server=mpilgrim
The first.py looks like this
def buildConnectionString(params):
"""Build a connection string from a dictionary of parameters.
Returns string."""
return ";".join(["%s=%s" % (k, v) for k, v in params.items()])
if __name__ == "__main__":
myParams = {"server":"mpilgrim", \
"database":"master", \
"uid":"sa", \
"pwd":"secret" \
}
print buildConnectionString(myParams)
And my codes worked, now I am in python shell
Python 2.7.2 (default, Dec 19 2012, 16:09:14) [GCC 4.4.6] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import amuse
>>>
So if I want the output of any code here, how do I proceed?
I had a program saved in my Pictures/practicepython
directory, how can I call that particular .py
files in python shell?
with import command, I am getting this error msg
Python 2.7.2 (default, Dec 19 2012, 16:09:14)
[GCC 4.4.6] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import amuse
>>> import first
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named first
>>>
Upvotes: 2
Views: 307
Reputation: 30151
If a Python module is designed properly, it will have a few lines like this, usually near the end of the module:
if __name__ == '__main__':
main() # or some other code here
Assuming first.py
looks like that, you can just call the main()
function:
>>> import first
>>> first.main()
Note that main()
might raise SystemExit
, which will cause the REPL to exit. If this matters to you, you can catch it with a try
block:
>>> import first
>>> try:
... first.main()
... except SystemExit:
... pass
Unfortunately, some modules don't have a proper main()
function (or anything similar), and simply put all their top-level code in the if
. In that case, there's no straightforward way to run the module from the REPL, short of copying the code.
If a Python module is not designed properly at all, it will run as soon as you import it. This is usually considered a Bad Thing because it makes it harder for others to use the module programmatically (e.g. calling the module's functions, instantiating its classes, etc.).
Upvotes: 2