python使用另一个文件中的变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14573021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:51:48  来源:igfitidea点击:

python using variables from another file

python

提问by Benjamin James

I'm new and trying to make a simple random sentence generator- How can I pull a random item out of a list that is stored in another .py document? I'm using

我是新手,正在尝试制作一个简单的随机句子生成器 - 如何从存储在另一个 .py 文档中的列表中提取随机项目?我正在使用

random.choice(verb_list) 

to pull from the list. How do I tell python that verb_list is in another document?

从列表中拉出。我如何告诉 python verb_list 在另一个文档中?

Also it would be helpful to know what the principle behind the solution is called. I imagine it's something like 'file referencing' 'file bridging' etc..

了解解决方案背后的原理也很有帮助。我想它类似于“文件引用”“文件桥接”等。

采纳答案by Kartik

You can import the variables from the file:

您可以从文件中导入变量:

vardata.py

变量数据文件

verb_list = [x, y, z]
other_list = [1, ,2, 3]
something_else = False

mainfile.py

主文件.py

from vardata import verb_list, other_list
import random

print random.choice(verb_list) 

you can also do:

你也可以这样做:

from vardata import *

to import everything from that file. Be careful with this though. You don't want to have name collisions.

从该文件导入所有内容。不过要小心。您不想发生名称冲突。

Alternatively, you can just import the file and access the variables though its namespace:

或者,您可以只导入文件并通过其命名空间访问变量:

import vardata
print vardata.something_else

回答by andrewdotn

It's called importing.

这叫进口。

If this is data.py:

如果这是data.py

verb_list = [
    'run',
    'walk',
    'skip',
]

and this is foo.py:

这是foo.py

#!/usr/bin/env python2.7

import data
print data.verb_list

Then running foo.pywill access verb_listfrom data.py.

然后运行foo.py将访问verb_listdata.py



You might want to work through the Modules section of the Python tutorial.

您可能想要完成Python 教程模块部分



If verb_listis stored in a script that you want to do other things too, then you will run into a problem where the script runs when all you'd like to do is import its variables. In that case the standard thing to do is to keep all of the script functionality in a function called main(), and then use a magic incantation:

如果verb_list存储在脚本中并且您还想做其他事情,那么您将遇到脚本运行的问题,而您只想导入其变量。在这种情况下,标准的做法是将所有脚本功能保存在一个名为 的函数中main(),然后使用魔法咒语:

verb_list = [
    'run',
    'walk',
    'skip',
]

def main():
    print 'The verbs are', verb_list

if __name__ == '__main__':
    main()

Now the code in main()won't run if all you do is import data. If you're interested, Python creator Guido van Rossum has written an article on writing more elaborate Python main()functions.

现在,main()如果您所做的只是import data. 如果您有兴趣,Python 创建者 Guido van Rossum 写了一篇关于编写更精细的Pythonmain()函数的文章。