1

I have a python script with a parse argument 'client_k.py'. To run it I write in the terminal python client_k 1. If I want to run 100 clients at the same time in the terminal, is there a way to make it apart from writing python client_k.py 1 & python client_k.py 2 & ... & python client_k.py 100 by hand? Thanks in advance.

deceze
  • 510,633
  • 85
  • 743
  • 889
Jesus M.
  • 33
  • 3

1 Answers1

0

You could create a new python script with a for to run you script several times.

client_k.py example:

def client_k(args=None):
    parser = argparse.ArgumentParser()
    parser.add_argument('my_arg')
    args = parser.parse_args(args=args)
    print('My arg:',args.my_arg)

if __name__ == '__main__':
    client_k()

run_client_k.py:

from client_k import client_k

for i in range(100):
    client_k([str(i)])

If you run it, your output would be:

My arg: 0
My arg: 1
My arg: 2
My arg: 3
...
My arg: 99

Or, if you have to execute all the commands at once such as in your description, you could do it using a subprocess:

import subprocess
bashCmd = ''
n = 10 # number of executions
for i in range(n):
    bashCmd +='python client_k.py '+str(i)+' '
    if i != n-1:
        bashCmd +='& ' # Not adding & for the last command

ret = subprocess.run(bashCmd, capture_output=True,shell=True)
print(ret.stdout.decode())
brenodacosta
  • 389
  • 2
  • 13
  • 1
    The `Popen` + `communicate` sequence is just a brittle incomplete reimplementation of `subprocess.check_output`. Like the documentation suggests, you should probably avoid `Popen` where you can, perhaps in favor of the more general-purpose and newer `subprocess.run`. – tripleee Jun 21 '22 at 14:23