-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
    Put the logic in `Script1.py` into a function – ti7 Feb 25 '21 at 22:07
  • Does this answer your question? [Why is Python running my module when I import it, and how do I stop it?](https://stackoverflow.com/questions/6523791/why-is-python-running-my-module-when-i-import-it-and-how-do-i-stop-it) – ti7 Feb 25 '21 at 22:14

2 Answers2

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

ti7
  • 16,375
  • 6
  • 40
  • 68
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.

Rallyx
  • 38
  • 8