简体   繁体   English

Python:从模块导入时生成不同的随机选择(不同的 python 文件) - 保持相同的 output

[英]Python: generate a different random choice when importing from module (different python file) - Keep getting same output

I have a code for choosing different comments from a list, which is stored in a separate python file, like comments.py:我有一个用于从列表中选择不同评论的代码,该列表存储在单独的 python 文件中,例如 comments.py:

import random

theitems = ['a','b','c','d','e','f']

commentpick = random.choice(theitems)

I have the following code in the main file:我在主文件中有以下代码:

from comments import commentpick

for a in commentboxes:
   a.send_keys(commentpick)
        

However the same comments will be returned for all the 'a' in commentboxes: [eg.但是,对于评论框中的所有“a”,将返回相同的评论:[例如。 5 inputs, 'a', 'a', 'a', 'a', 'a'] 5个输入,'a','a','a','a','a']

It only works if i import random and do it on the main file, like this:它只有在我随机导入并在主文件上执行时才有效,如下所示:

for a in commentboxes:
       a.send_keys(random.choice(theitems))

then the result will be varied, [eg.那么结果会有所不同,[例如。 'a', 'c', 'e', 'd', 'f'] 'a'、'c'、'e'、'd'、'f']

Is there any way that I will be able to write a.send_keys(commentpick) directly without doing the random.choice in the main file but still get different results each time?有什么方法可以让我直接编写 a.send_keys(commentpick) 而无需在主文件中执行 random.choice 但每次仍然得到不同的结果? Thanks.谢谢。

you should put你应该把

commentpick = random.choice(theitems) commentpick = random.choice(theitems)

in function, by that you can call random function each time to call the function you build在 function 中,您可以调用随机 function 每次调用您构建的 function

for example: comments.py例如:comments.py

def commentpick():
    theitems = ['a','b','c','d','e','f']
    commentpick = random.choice(theitems)
    return commentpick

and in your main file:在你的主文件中:

from comments import commentpick

for a in commentboxes:
    a.send_keys(commentpick())

your problem is you just called once and save the value and used many times.您的问题是您只需调用一次并保存该值并多次使用。

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

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