Command Line With Variables In Subprocess
Solution 1:
I think you get lost with the string concatenation... you have to ways to execute a cmd with run
or 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 beforeif you want that your program will be launched from the shell then you need to add a kwrags parameter
shell=True
, defaultFalse
. In this case, depending if you choose theargs
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"