1

I want to run a python script inside another script's for-loop every loop. The below code works but only for the first loop ("run_this_script.py" only executes when i=1). How can I get it to run every iteration?

for i in range (1,10)
   import run_this_script.py
Retsied
  • 79
  • 8
  • 1
    you are either going to have to use a subprocess, or you will need to edit the script to encapsulate the logic into a function – Alexander Jul 23 '22 at 04:21
  • Guess you could run it with `os.system('path-to-python-file')` – Matheus Delazeri Jul 23 '22 at 04:21
  • Relevant: https://stackoverflow.com/questions/37067414/python-import-multiple-times – Mandera Jul 23 '22 at 04:30
  • I assume you meant `import run_this_script` (no .py). Is this your own script you are trying to run? You could potentially put whatever this script does into a function and call that repeatedly. – tdelaney Jul 23 '22 at 04:30
  • Correct, yes no ".py" at the end, sorry. When I try os.system("path") it opens the file in VSC but doesn't run (I'm using Spyder IDE) – Retsied Jul 23 '22 at 04:49
  • execfile("path") seems to work, although is weird because the code analysis shows a red cross icon at the line number and says "Undefined name 'execfile'" but it runs.. – Retsied Jul 23 '22 at 05:17
  • Does this answer your question? "[Run a Python script from another Python script, passing in arguments](//stackoverflow.com/q/3781851/90527)", "[What is the best way to call a script from another script?](//stackoverflow.com/q/1186789/90527)" – outis Jul 23 '22 at 06:59
  • As mentioned in at [least one answer](//stackoverflow.com/a/1186826/90527), you should consider instead defining a function (or class) in the other script that is then called from the loop body (rather than launching a whole new process). – outis Jul 23 '22 at 07:03

1 Answers1

0
import os

for i in range(1, 10):
   print(f'{i}. ')
   os.system('python run_this_script.py')
Waket Zheng
  • 5,065
  • 2
  • 17
  • 30
  • This works, although I have some print functions in the script being called I'd like to see that won't appear in the Spider console since os.system runs in the background. If I use functions/subprocess will this also be true? – Retsied Jul 23 '22 at 17:09