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

如何在Linux环境下在pythonshell中执行python程序,python,Python,我使用一个名为的天体物理软件,它使用python命令行。我已经得到了在终端中导入娱乐的二进制版本。现在,如果我想在任何目录中运行一个保存的python程序,我该如何调用它 以前我用在终端 python first.py pwd=secret;database=master;uid=sa;server=mpilgrim 第一个.py看起来像这样 def buildConnectionString(params): """Build a connection string from a

我使用一个名为的天体物理软件,它使用python命令行。我已经得到了在终端中导入娱乐的二进制版本。现在,如果我想在任何目录中运行一个保存的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
>>> 
Python 2.7.2(默认,2012年12月19日,16:09:14)
[GCC 4.4.6]关于linux2
有关详细信息,请键入“帮助”、“版权”、“信用证”或“许可证”。
>>>进口娱乐
>>>先进口
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
ImportError:没有先命名的模块
>>> 

如果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模块的设计根本不正确,那么它将在导入后立即运行。这通常被认为是一件坏事,因为它使其他人更难以编程方式使用模块(例如,调用模块的函数、实例化其类等)。

first.py更新为我的问题以及我看到的构建良好的问题。但是如果我按照你的指示去做,它首先会给我带来错误,我也在帖子中更新了,你能检查一下并告诉我如何修复吗?@TazkeraHaqueTrina:你需要和
first.py
在同一个目录中,或者你需要安装(复制)
first.py
进入中列出的目录之一。您能告诉我怎么做吗?我不知道如何复制文件和sys.path。@Tazkera:最简单的方法是将
first.py
复制到当前目录中。在Unix命令提示符下,这是通过
cp-t完成的。path/to/first.py
。有关更多详细信息,请参见或在命令行中键入
man cp