python - 如何在Linux导入特殊环境的python shell中执行python程序

标签 python

我使用一款名为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模块根本没有正确设计,它一导入就会运行。这通常被认为是一件坏事,因为它使得其他人更难以编程方式使用模块(例如调用模块的函数、实例化其类等)。

关于python - 如何在Linux导入特殊环境的python shell中执行python程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27274632/

相关文章:

python - 在linux上运行autobahn python会出现异常。AttributeError : Router instance has no attribute 'broker'

python - render_template 无法 jsonify 对象

python - 添加后列表的最后一项没有改变

python - 缩进错误 : expected an indented block

python - Numpy 数组索引意外行为

python - 将 DataFrame 中的困惑日期字符串转换为 python 和 pandas 中的 `datetime`

javascript - 为什么要区分单行注释和多行注释?

python - matplotlib:设置主要和次要刻度线强制相同的 x 和 y 刻度

python - 使用 fnmatch 查找具有名称模式的所有文件夹

python - 将 sympy 与 esky 一起使用时生成错误