简体   繁体   English

如何从 Python 中的文件调用函数?

[英]How to call functions from a file in Python?

I am very new to Python.我对 Python 很陌生。 I've learned recently that we could store all our defined functions in one file and call them up when we need it.我最近了解到,我们可以将所有定义的函数存储在一个文件中,并在需要时调用它们。 I'm using Idle on Windows.我在 Windows 上使用空闲。

Where should I store the.py file that will contain all the functions so they can be accessed from Idle, and how should I call it?我应该将包含所有函数的 .py 文件存储在哪里,以便可以从 Idle 访问它们,我应该如何调用它?

Some Folder
|
  - my_funcs.py
|
  - other.py

other.py 其他

from my_funcs import somefunc
somefunc("An Argument")

my_funcs.py my_funcs.py

def somefunc(s):
    print "SomeFunction:%s"%s

then run other.py 然后运行other.py

The file must be on your PYTHONPATH. 该文件必须在您的PYTHONPATH上。 You need to set that in your environment. 您需要在您的环境中进行设置。 eg if your file is: 例如,如果您的文件是:

C:/path/to/myfile.py

Then you need to make sure that C:/path/to is on PYTHONPATH. 然后,您需要确保C:/path/to在PYTHONPATH上。 Then, in another script, you can import myfile via: 然后,在另一个脚本中,您可以通过以下方式导入myfile

import myfile

Now you can use a function ( func ) defined in myfile as: 现在,您可以将在myfile定义的函数( func )用作:

myfile.func()

Say you are testing a function and you would like to see it working on the fly: this is the usual sequence假设您正在测试 function 并且您希望看到它在运行中运行:这是通常的顺序

  • you have "IDLE" open as main shell你有“空闲”作为主打开 shell
  • from Idle you open a new file where you write your commands or a function从空闲打开一个新文件,在其中编写命令或 function
  • you make this module run from RUN -> MODULE or press F5你让这个模块从 RUN -> MODULE 运行或按 F5
  • this starts your module on Idle or generates an error warning (such as a wrong indentation)这会在空闲时启动您的模块或生成错误警告(例如错误的缩进)

Now it is 2 cases:现在是2种情况:

  • either your module is bare commands: then they will be executed immediately on Idle shell要么您的模块是裸命令:然后它们将在空闲 shell 上立即执行
  • or your module is a function, then you need to call it as it is meant to, with or without arguments;或者您的模块是 function,那么您需要按原样调用它,无论有无 arguments; eg: myFunction() or secondsInYears(5)例如: myFunction()secondsInYears(5)

That is what it all should be.这就是一切。

Comment .评论 Differently from compiling and testing in C, where you only need a text-editor to compile through Command line and a compiler (to avoid opening clunky dev-env's);与 C 中的编译和测试不同,您只需要一个文本编辑器即可通过命令行和编译器进行编译(以避免打开笨重的 dev-env); in Python paradoxically such a workflow turns even too demanding to be an alternative to the native IDLE as you need to be specific each time.在 Python 中,矛盾的是,这样的工作流程变得过于苛刻,无法替代原生 IDLE,因为您每次都需要具体。 I hope it helps我希望它有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM