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

2024-10-03 04:27:24 发布

您现在位置:Python中文网/ 问答频道 /正文

例如,我在PyCharm中有:

脚本1.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()

脚本2.py

import YtTest.py
import time

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

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


Tags: pathfrompyimport脚本timedriverselenium
2条回答

您可以在脚本1中创建如下函数:

脚本1.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()

脚本2.py

from script1 import my_function

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

以适应你的需要

通常,人们会为此使用函数

您也可以通过巧妙地使用__name__属性独立运行脚本

脚本1.py

def my_function():
    "whatever logic"

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

脚本2.py

from script1 import my_function

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

if __name__ == "__main__":
    main()

此代码样式对于各种与导入相关的活动非常有用,例如unit testing

相关问题 更多 >