简体   繁体   English

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

[英]python using variables from another file

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?我是新手,正在尝试制作一个简单的随机句子生成器 - 如何从存储在另一个 .py 文档中的列表中提取随机项目? I'm using我在用着

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..我想它类似于“文件引用”“文件桥接”等。

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

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.py will access verb_list from data.py .然后运行foo.py将访问verb_listdata.py


You might want to work through the Modules section of the Python tutorial .您可能想要完成Python 教程模块部分


If verb_list is 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.如果verb_list存储在您还想做其他事情的脚本中,那么您将遇到脚本运行的问题,而您只想导入其变量。 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:在这种情况下,标准的做法是将所有脚本功能保存在一个名为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 .现在,如果您所做的只是import data ,则main()的代码将不会运行。 If you're interested, Python creator Guido van Rossum has written an article on writing more elaborate Python main() functions .如果您有兴趣,Python 创造者 Guido van Rossum 写了一篇关于编写更精细的Python main()函数的文章

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

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