如何通过另一个python脚本循环N次python脚本?[duplicate]

lhcgjxsq  于 2023-03-11  发布在  Python
关注(0)|答案(2)|浏览(180)

此问题在此处已有答案

What is the best way to call a script from another script? [closed](16个答案)
Is it possible to make a for loop without an iterator variable? (How can I make make code loop a set number of times?)(14个答案)
23小时前关门了。
例如,我在PyCharm中有:
Script1.py

from selenium import webdriver
import time

PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://www.youtube.com/?hl=pl&gl=PL")
time.sleep(1)
driver.close()

Script2.py

import YtTest.py
import time

i = 0
while i < n:
    execfile("YtTest.py")
    i += 1

如何正确导入并执行Script1.py并循环N次(全部在www.example.com中Script2.py)?

6bc51xsx

6bc51xsx1#

通常,我们会使用函数来执行此操作
您也可以通过巧妙地使用__name__属性来独立运行脚本
script1.py

def my_function():
    "whatever logic"

if __name__ == "__main__":  # this guard prevents running on import
    my_function()

script2.py

from script1 import my_function

def main():
    for _ in range(10):  # run my_function() 10 times
        my_function()

if __name__ == "__main__":
    main()

这种代码风格对于各种与导入相关的活动(如单元测试)非常有用

zbwhf8kr

zbwhf8kr2#

您可以在脚本1中创建一个函数,如下所示:
Script1.py

from selenium import webdriver
import time

PATH = "C:\Program Files (x86)\chromedriver.exe"

def my_func():
    driver = webdriver.Chrome(PATH)
    driver.get("https://www.youtube.com/?hl=pl&gl=PL")
    time.sleep(1)
    driver.close()

if __name__ == "__main__":
    my_func()

Script2.py

from script1 import my_function

i = 0
while i < n:
    script1.my_function()
    i += 1

以适应您的需求。

相关问题