简体   繁体   English

如何将外部 python 文件导入另一个 python 文件?

[英]How to import external python file to another python file?

I would like to import one python file into another and then compile the main file.我想将一个 python 文件导入另一个文件,然后编译主文件。 How can I do this?我怎样才能做到这一点?

MWE: Suppose I would like to calculate factorial of a positive integer. MWE:假设我想计算正 integer 的阶乘。 It can be done successfully by the following way:可以通过以下方式成功完成:

n=5
fact = 1
if n < 0:
    print("Sorry, factorial does not exist for negative numbers")
elif n == 0:
    print("The factorial of 0 is 1")
else:
    for i in range(1,n + 1):
        fact = fact*i
    print "%d!=%d"%(n,fact)

But I would like to create a secondary file say "auxfile.py" containing:但我想创建一个辅助文件说“auxfile.py”,其中包含:

fact = 1
if n < 0:
    print("Sorry, factorial does not exist for negative numbers")
elif n == 0:
    print("The factorial of 0 is 1")
else:
    for i in range(1,n + 1):
        fact = fact*i
    print "%d!=%d"%(n,fact)

And another main file say "main.py" containing:另一个主文件说“main.py”,其中包含:

print "Required factorial is given below:"
for n in range(30): 
    import auxfile.py

How can I do this?我怎样才能做到这一点?
Note: I know defining a function the whole process can be done in a single file.注意:我知道定义一个 function 整个过程可以在一个文件中完成。 But I have to do a large program where I would like to apply this process.但我必须做一个大型程序,我想在其中应用这个过程。

Simple, just use the import method.很简单,只需使用import方法即可。 To make your life easier simply copy the.py file you would like to import to the same folder that the file you want to import the other code file into is in.为了让您的生活更轻松,只需将要导入的 .py 文件复制到要导入其他代码文件的文件所在的文件夹中。

Eg if you wanted to import happy.py to sad.py simply do:例如,如果您想将 happy.py 导入到 sad.py,只需执行以下操作:

import happy

This would give the following traceback (look at example below):这将给出以下回溯(请看下面的示例):

Hello

Although, this will instantly run everything outside of any def loops in the.py file.虽然,这将立即运行 .py 文件中任何 def 循环之外的所有内容。 Therefore, if you wanted to run a single def loop in the file, then use the following code:因此,如果您想在文件中运行单个 def 循环,请使用以下代码:

Example contents of happy.py: happy.py 的示例内容:

print("Hello")
def okay():
    print("okay")

If you did:如果你这样做了:

happy.okay()

This would give you the following traceback:这将为您提供以下回溯:

Hello
okay

TIP FOR YOUR CODE IN MAIN.PY: You did:提示您在 MAIN.PY 中的代码:您做了:

print "Required factorial is given below:" whereas you forgot the brackets. print "Required factorial is given below:" 而你忘记了括号。 You should use: print("Required factorial is given below:") This will avoid future errors!你应该使用: print("Required factorial is given below:")这将避免未来的错误!

Hope this helps!希望这可以帮助!

you can do it like this:你可以这样做:

auxfile.py辅助文件.py

def factorial(n):
    fact = 1
    if n < 0:
        print("Sorry, factorial does not exist for negative numbers")
    elif n == 0:
        print("The factorial of 0 is 1")
    else:
        for i in range(1,n + 1):
            fact = fact*i
            print "%d!=%d"%(n,fact)

in your main.py:在你的 main.py 中:

from auxfile import factorial

print "Required factorial is given below:"
for n in range(30): 
    factorial(n)

If you're trying to avoid using a function--maybe you could wrap your entire code in the for loop?如果您试图避免使用函数——也许您可以将整个代码包装在 for 循环中? If it is not as simple as a for-loop, maybe you could copy your main code into the other file above it.如果它不像 for 循环那么简单,也许你可以将你的主代码复制到它上面的另一个文件中。

For example: Before:例如: 之前:

file1: "Your main code that wants to call the code below" file1: "Your main code that wants to call the code below"
file2: "Your code that is too cumbersome to convert to a function" file2: "Your code that is too cumbersome to convert to a function"

After:后:
file1:文件1:

"Your main code that wants to call the code below"
 for n in range(30):
     "Your code that is too cumbersome to convert to a function"

There's still quite an ugly solution, which is to use the exec built-in function.还有一个相当难看的解决方案,就是使用exec内置的 function。

First of all, you read the code from your file:首先,您从文件中读取代码:

with open("auxiliary.py", 'r') as f:
    content = f.readlines()

Then you filter out the lines you don't want, so that content is a string containing your Python code, that is:然后你过滤掉你不想要的行,这样content就是一个包含你的 Python 代码的字符串,即:

# The following evaluates to True
content == 'fact = 1\nif n < 0:\n    print("Sorry, factorial does not exist for negative numbers")\nelif n == 0:\n    print("The factorial of 0 is 1")\nelse:\n    for i in range(1,n + 1):\n        fact = fact*i\n    print "%d!=%d"%(n,fact)'

Then you can just call the exec function, which will act as if the lines were included in lieu of the call of the function:然后你可以只调用exec function,它的作用就像包含这些行来代替 function 的调用:

exec content # Or exec(content), both seems to work in Python 2.7

See here for a further explanation.有关进一步的说明,请参见此处

Note that you will have access to fact and every other variables, just as if you had written these lines in your main file.请注意,您将可以访问fact和所有其他变量,就像您在主文件中编写了这些行一样。

Be aware that this might get dangerous: if you don't formally identify which lines to execute (like, put a comment as an identifier, or if the auxiliary file never changes), you may end up running some code from your auxiliary file you dont want to.请注意,这可能会变得危险:如果您没有正式确定要执行哪些行(例如,将注释作为标识符,或者如果辅助文件永远不会更改),您最终可能会从您的辅助文件中运行一些代码不想。

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

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