Skip to content Skip to sidebar Skip to footer

Command Line With Variables In Subprocess

I want to run this command with variables inside a subprocess in a script. The variable is: filenames[k] filenames have many names (strings), which I can go through with k. The co

Solution 1:

I think you get lost with the string concatenation... you have to ways to execute a cmd with runor such: either as a string or as a list (as a list is usually more readable!)

Case: args as string

cmd = f'python3 train.py "C:\Users\Tommy\data\\{filenames[k]}" "C:\Users\Tommy\data\\{filenames[k]}+_model" --choice A'

subprocess.run(args=cmd, shell=True)

Case: args as list

cmd = f'python3 train.py "C:\Users\Tommy\data\\{filenames[k]}" "C:\Users\Tommy\data\\{filenames[k]}+_model" --choice A'

cmd = cmd.split(' ') # provided that no white spaces in the paths!!

subprocess.run(args=cmd, shell=False)

Remark:

  • it is very handy the "new" string concatenation f"smt {variable} smt else" where variable is a variable defined before

  • if you want that your program will be launched from the shell then you need to add a kwrags parameter shell=True, default False. In this case, depending if you choose the args to be either a string or a list, you should be then more careful: from the docs "if shell is True, it is recommended to pass `args as a string rather than as a sequence"

  • Have a look to the docs, at Popen Constructor, for a full description of the signature

Post a Comment for "Command Line With Variables In Subprocess"