How to Pass a List Variable to Subprocess.Call Command in Python

I need to give variable names to subprocess.call command

First, construct the full file name properly:

full_name = os.path.join(dir_path, file_name)

Then, pass a list as the first argument to call:

subprocess.call(["rm", full_name])

(In real life, you wouldn't use call here at all; you'd use os.remove(full_name).)

Passing a variable to a subprocess call

There are two things wrong here:

  1. Your string concatenation syntax is all wrong; that's not valid Python. You probably wanted to use something like:

    command = "tail -n " + str(myvariable) + " test.txt >> testmod.txt"

    where I assume that myvariable is an integer, not a string already.

    Using string formatting would be more readable here:

    command = "tail -n {} test.txt >> testmod.txt".format(myvariable)

    where the str.format() method will replace {} with the string version of myvariable for you.

  2. You need to tell subprocess.call() to run that command through the shell, because you are using >>, a shell-only feature:

    call(command, shell=True)

Command line with variables in subprocess

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



Related Topics



Leave a reply



Submit