有没有一种方法可以从文件中导入项目,而无需在python中运行该文件中的所有代码 [英] Is there a way to import items from a file without running all of the code in that file in python

查看:72
本文介绍了有没有一种方法可以从文件中导入项目,而无需在python中运行该文件中的所有代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个文件,file1和file2.

I have two files, file1 and file2.

文件2是这样的:

print "Why is this printing"

var = 7

文件1是这个:

from file2 import var

print var

当我运行这段代码时,它输出以下内容:

When I run this code, it outputs the following:

>>>Why is this printing
>>>7

有没有一种方法可以在不运行var声明上方的代码的情况下从file2获取var?

Is there a way I can obtain var from file2 without running the code above the declaration of var?

推荐答案

如果您不希望在导入模块时运行代码,请将其放在函数中:

If you don't want code to run when a module is imported, put it in a function:

def question():
    print "Why is this printing"

如果您希望函数在模块通过命令行传递给python解释器时运行,请将其放在条件表达式块中:

If you want the function to run when the module is passed to the python interpreter on the command line, put it in a conditional expression block:

if __name__ == '__main__':
    question()

例如

c:/> python file2.py
Why is this printing

这篇关于有没有一种方法可以从文件中导入项目,而无需在python中运行该文件中的所有代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆