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:
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 ofmyvariable
for you.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 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
Related Topics
How to Control the Keyboard and Mouse with Python
Why Does Python "Preemptively" Hang When Trying to Calculate a Very Large Number
How to Get the Owner and Group of a Folder with Python on a Linux MAChine
How to Make Python Script Press 'Enter' When Prompted on Shell
What Conditions Result in an Opened, Nonblocking Named Pipe (Fifo) Being "Unavailable" for Reads
Python: What Are the Nearest Linux and Osx Equivalents of Winsound.Beep
Python Memory Debugging with Gdb
How to Handle Os.System Sigkill Signal Inside Python
Faster Way to Find Large Files with Python
How to Send Input on Stdin to a Python Script Defined Inside a Makefile
Virtualenv Uses Wrong Python, Even Though It Is First in $Path