0

I have 10 python file (1.py, 2.py, 3.py .... 10.py) i want to start random with python script, with while true. For ex. script start random py file (4.py) after finish the commands start again new random file (1.py) I want it to spin like this forever.

I try with this command but not working.

while True :
    p = subprocess.Popen(['python', 'randint(1,10).py'])

Script give error

python: can't open file '<randint<1,3>>.py':

Enes Aksu
  • 5
  • 2

1 Answers1

0

Try

while True :
    p = subprocess.Popen(['python', str(randint(1,10))+'.py'])

randint(1,3) is a function, not a string, so it should be outside ''s. Then, I use str() to convert the number returned by randint to a string. Finally, I added + to concatenate str(randint(1,3)) and '.py'! Also, if you have 10 files, then the second parameter of randint should be 10.

Yulia V
  • 3,507
  • 10
  • 31
  • 64
  • 1
    Or better use an f-string: `p = subprocess.Popen(['python', f'{randint(1,10)}.py'])` – Matthias Oct 08 '22 at 19:06
  • Hello, first of all thank you very much for your help @Yulia V . How can I wait for a python script to finish its task? In this way, the python file is opened unlimitedly. Temporarily because I know the process takes an estimated 70 seconds I used this code: `p = subprocess.Popen(['python', str(randint(1,3))+'.py']) time.sleep(70) p.terminate()` – Enes Aksu Oct 08 '22 at 19:21
  • 1
    @EnesAksu would you like to ask it as a separate question? Quick answer though: if your script files contain functions, you can import the files as modules and call the functions they contain instead of launching separate python processes. This might help. If not, please ask a separate question :) – Yulia V Oct 08 '22 at 20:38