File.py包含一个名为function的函数。如何导入?

from file.py import function(a,b)

上面给出了一个错误:

ImportError:没有名为'file.py'的模块;文件不是包


当前回答

如果你的文件在不同的包结构中,你想从不同的包中调用它,那么你可以这样调用它:

假设你的python项目中有以下包结构:

在python文件中你有一些函数,比如:

def add(arg1, arg2):
    return arg1 + arg2

def sub(arg1, arg2) :
    return arg1 - arg2

def mul(arg1, arg2) :
    return arg1 * arg2

你想从Example3.py调用不同的函数,那么你可以通过以下方式做到:

在Example3.py - file中定义import语句用于导入所有函数

from com.my.func.DifferentFunction import *

或者定义想要导入的每个函数名

from com.my.func.DifferentFunction import add, sub, mul

然后在Example3.py中调用execute函数:

num1 = 20
num2 = 10

print("\n add : ", add(num1,num2))
print("\n sub : ", sub(num1,num2))
print("\n mul : ", mul(num1,num2))

输出:

 add :  30

 sub :  10

 mul :  200

其他回答

首先将文件保存为.py格式(例如my_example.py)。 如果那个文件有函数,

def xyz():

        --------

        --------

def abc():

        --------

        --------

在调用函数中,您只需键入下面的行。

file_name: my_example2.py

============================

import my_example.py


a = my_example.xyz()

b = my_example.abc()

============================

如果你的文件在不同的包结构中,你想从不同的包中调用它,那么你可以这样调用它:

假设你的python项目中有以下包结构:

在python文件中你有一些函数,比如:

def add(arg1, arg2):
    return arg1 + arg2

def sub(arg1, arg2) :
    return arg1 - arg2

def mul(arg1, arg2) :
    return arg1 * arg2

你想从Example3.py调用不同的函数,那么你可以通过以下方式做到:

在Example3.py - file中定义import语句用于导入所有函数

from com.my.func.DifferentFunction import *

或者定义想要导入的每个函数名

from com.my.func.DifferentFunction import add, sub, mul

然后在Example3.py中调用execute函数:

num1 = 20
num2 = 10

print("\n add : ", add(num1,num2))
print("\n sub : ", sub(num1,num2))
print("\n mul : ", mul(num1,num2))

输出:

 add :  30

 sub :  10

 mul :  200

在我的主脚本detectiverb .py文件中,我需要调用passGen函数,生成密码哈希,该函数在模块\passwordGen.py下

对我来说最快最简单的解决办法是

下面是我的目录结构

所以在detectiveROB.py中,我用下面的语法导入了我的函数

从模块。passwordGen导入passGen

导入时不要写.py。

让file_a.py包含一些函数:

def f():
  return 1

def g():
  return 2

要将这些函数导入file_z.py,请执行以下操作:

from file_a import f, g

MathMethod.Py内部。

def Add(a,b):
   return a+b 

def subtract(a,b):
  return a-b

内部Main.Py

import MathMethod as MM 
  print(MM.Add(200,1000))

输出:1200