-1

For example I have in 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

How to make import properly and execute Script1.py and loop it N times (all in Script2.py)?

2

2 Answers 2

1

Commonly, one would use a function for this

You can run the script independently by clever use of the __name__ property too

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()

This code style is extremely useful for a variety of import-related activities, such as unit testing

Sign up to request clarification or add additional context in comments.

Comments

1

You could make a function in script 1 like this:

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

To adapt with your needs.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.