0

我是 python 新手,我正在尝试执行我的第一个 python 函数,但不幸的是我遇到了一些问题,无法从这个简单的函数中获得预期的结果,请帮助我显示该函数的输出。下面发布的函数是用 python 编辑器编写的

我不知道如何从 python shell 调用这个函数来显示它的结果。

蟒蛇代码:

def printme( str ):
    "This prints a passed string into this function"
    print str;
    return;

蟒蛇壳:

>>> printme("d")
>>> Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
printme("d")
NameError: name 'printme' is not defined
4

5 回答 5

4
$ cd /path/to/your/filename.py
$ python
>>> from filename import printme
>>> printme("hello world!")
于 2013-04-30T09:25:18.860 回答
3

您必须在启动解释器时加载脚本。从终端外壳(如 bash 或 zsh):

$ python2 -i script.py 
>>> printme("hola")
hola
>>> 



附带说明,您不必用分号终止语句(如果它们在自己的行中),也不必return在函数末尾附加语句(因为缩进和行分隔在 Python 中很重要) .

于 2013-04-30T09:21:27.313 回答
0

如果您使用任何用于 python 的 IDE,您实际上可以通过按下/键入 Run(F5 等效项)在 python shell 中运行该程序。如果不是这种情况,请继续阅读:

  1. 在您选择的任何位置将程序另存为 test.py(或任何其他名称)。
  2. 启动 python 外壳
  3. >>导入系统
  4. >>系统路径
  5. 如果您保存 test.py 的目录出现在 sys.path 的输出中,请转到步骤 7
  6. sys.path.append("你保存test.py的目录地址")
  7. >>import test #note .py 被移除
  8. >>test.printme("Hello World")

sys.path 是包含 python 查找导入模块的所有目录的列表。通过添加(附加)您的目录,您可以确保 test.py 可以作为模块测试导入。然后你可以调用 test.py 的任何函数为 test.fucn()

在第 7 步,您可以这样做: 7. >>from test import printme 8. >>printme("Hello again")

于 2013-04-30T09:32:04.813 回答
0

如果您使用的是 unix shell:

$ cd C:\yourpath
$ python mypythonfile.py

如果您使用的是交互模式,那么:

execfile("C:\\myfolder\\myscript.py")

在交互模式下还有很长的路要走,但如果您更喜欢设置默认路径:

import os
prevPath = os.getcwd() #save the default path
myPath = "C:\myPython\somepath"
os.chdir(myPath) #set your python path
execfile("myscript.py") #executes the file
#os.chdir(prevPath) will restore the default path

还是我误解了你的问题?如果你只是想运行一个函数,就这么简单..

>>> def printme(str):
    print str


>>> printme("Hello world!")
Hello world!
>>> 

希望这可以帮助!

于 2013-04-30T10:03:45.183 回答
0

我的python知识非常低......,你的问题来自本教程,我必须在Linux shell上写你的例子,我没有问题......

>>> def printme(str):
        This print .......................
        print str
        return

>>> printme('d')
d

我是怎么理解的,你的问题是你要证明在你的代码保存之前使用空闲控制台和 Linux shell ......我认为,shellfly 和 alKid 的例子描述了直觉,你怎么能解决你的问题.. .

对不起我的英语......

于 2017-06-09T14:47:32.707 回答