我使用了一款名为 AMUSE 的天体物理学软件,它使用 python 命令行。我有在终端中导入 amuse 的二进制版本。现在如果我想在任何目录下运行一个保存的python程序,我该如何调用它?
以前我在终端里用过
python first.py
pwd=secret;database=master;uid=sa;server=mpilgrim
第一个.py 看起来像这样
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)
我的代码有效,现在我在 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
>>>
所以如果我想在这里输出任何代码,我该如何进行?
我在 Pictures/practicepython 目录中保存了一个程序,如何在 python shell 中调用该特定的 .py 文件?
使用导入命令,我收到此错误消息
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
>>>
请您参考如下方法:
如果一个 Python 模块设计得当,它会有这样几行,通常在模块的末尾附近:
if __name__ == '__main__':
main() # or some other code here
假设 first.py 看起来像那样,您可以调用 main() 函数:
>>> import first
>>> first.main()
请注意,main() 可能引发 SystemExit,这将导致 REPL 退出。如果这对你很重要,你可以用 try block 来捕获它:
>>> import first
>>> try:
... first.main()
... except SystemExit:
... pass
不幸的是,有些模块没有合适的 main() 函数(或任何类似的函数),只是将它们所有的顶级代码放在 if 中。在这种情况下,除了复制代码外,没有直接的方法从 REPL 运行模块。
如果 Python 模块根本没有设计得当,它会在您导入后立即运行。这通常被认为是一件坏事,因为它使其他人更难以编程方式使用模块(例如调用模块的函数、实例化其类等)。
