espogian
espogian

Reputation: 607

Correct usage of subprocess.run() in Python

I would like to run these tree bash commands in Python:

sed $'s/\r//' -i filename
sed -i 's/^ *//; s/ *$//; /^$/d' filename
awk -F, 'NF==10' filename > temp_file && mv temp_file filename

I wrote the following code:

cmd_1 = ["sed $'s/\r//' -i", file]
cmd_2 = ["sed -i 's/^ *//; s/ *$//; /^$/d'", file]
cmd_3 = ["awk -F, 'NF==10'", file, "> tmp_file && mv tmp_file", file]

subprocess.run(cmd_1)
subprocess.run(cmd_2)
subprocess.run(cmd_3)

But I'm getting this error here:

FileNotFoundError: [Errno 2] No such file or directory: "sed $'s/\r//' -i": "sed $'s/\r//' -i"

What I'm getting wrong?

Upvotes: 0

Views: 372

Answers (2)

user4815162342
user4815162342

Reputation: 155505

If you provide the command as a list, then each argument should be a separate list member. Therefore:

cmd_1 = ["sed" r"s/\r//", "-i", file]
cmd_2 = ["sed" "-i" "s/^ *//; s/ *$//; /^$/d", file]
subprocess.run(cmd_1)
subprocess.run(cmd_2)

The last command requires the operators > and && provided by the shell, so you will need to also specify shell=True, and make the command a string:

cmd_3 = f"awk -F, NF==10 '{file}' > tmp_file && mv temp_file '{file}'"
subprocess.run(cmd_3, shell=True)

Upvotes: 2

blhsing
blhsing

Reputation: 107094

You have to use the shell=True parameter:

subprocess.run(cmd_1, shell=True)

Upvotes: 1

Related Questions