简体   繁体   English

Python 进口 function 与 package

[英]Python import function with package

I want to import a function from another python file.我想从另一个 python 文件导入一个 function。 The problem is that I either have to call it with file.function() or import it with from file import function .问题是我要么必须使用file.function()调用它,要么使用from file import function导入它。

Since my file contains only one function, I am looking for a way to import it directly with import file .由于我的文件只包含一个 function,我正在寻找一种直接使用import file导入它的方法。

I don't understand the problem.我不明白这个问题。 Why not just:为什么不只是:

from file import function

function(params)

Not sure why from file import function is an issue, but the only other way to do it (other than calling file.function() everythime) is to do from file import *不知道为什么from file import function是一个问题,但唯一的其他方法(除了调用file.function() )是from file import *

Not sure what the issue is with either option that you listed.不确定您列出的任一选项有什么问题。

What you can do is turn your module (the file with the function you want to import) into a script by adding if __name__ == "__main__": to the end of your file like so:您可以做的是通过将if __name__ == "__main__":添加到文件末尾,将您的模块(要导入的带有 function 的文件)转换为脚本,如下所示:

# file.py
def function(...):
    ...

if __name__ == "__main__":
    import sys
    function(sys.argv[1])

then import it as import file .然后将其作为import file

Reference: https://docs.python.org/3/tutorial/modules.html#executing-modules-as-scripts参考: https://docs.python.org/3/tutorial/modules.html#executing-modules-as-scripts

I personally don't see an issue with alternative you listed, but the docs do have this to say about what you're trying to achieve:我个人认为您列出的替代方案没有问题,但文档确实有关于您要实现的目标的说明:

This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).这通常用于为模块提供方便的用户界面,或用于测试目的(将模块作为脚本运行测试套件)。

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

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