在Linux环境下如何在pythonshell中执行python程序

2024-04-25 17:02:00 发布

您现在位置: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)

我的代码工作了,现在我在pythonshell中

 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目录中保存了一个程序,如何在pythonshell中调用特定的.py文件?你知道吗

使用import命令,我得到这个错误消息

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
>>> 

Tags: pyimport程序master目录终端foruid
1条回答
网友
1楼 · 发布于 2024-04-25 17:02:00

如果一个Python模块设计正确,它会有几行这样的代码,通常在模块末尾附近:

if __name__ == '__main__':
    main()  # or some other code here

假设first.py是这样的,您可以调用main()函数:

>>> import first
>>> first.main()

请注意,main()可能会引发SystemExit,这将导致REPL退出。如果这对您很重要,您可以使用try块来捕获它:

>>> import first
>>> try:
...     first.main()
... except SystemExit:
...     pass

不幸的是,有些模块没有合适的main()函数(或任何类似的函数),只是将它们的所有顶层代码放在if中。在这种情况下,除了复制代码之外,没有直接的方法从REPL运行模块。你知道吗

如果一个Python模块的设计完全不正确,那么它将在您导入它时立即运行。这通常被认为是一件坏事,因为它使其他人更难以编程方式使用模块(例如,调用模块的函数、实例化模块的类等)。你知道吗

相关问题 更多 >