Home > Back-end >  Python execute shell command with variables inside (quoted) command string
Python execute shell command with variables inside (quoted) command string

Time:10-21

I'm writing a python script to use a mappingfile (based on json) to replace strings within a txt file via sed:

import json
import sys
import subprocess

file_to_edit = str(sys.argv[1])
a_dictionary = {"a.b.c.d": "e.f.g.h"}

for pair in a_dictionary.items():
 orig = pair[0]    //"a.b.c.d"
 repl = pair[1]    //"e.f.g.h"

Now I want to execute the the following shellcommand (within the script): sed -i 's/orig/repl/g' filetoedit .

Or what I would type manually sed -i 's/a.b.c.d/e.f.g.h/g' datafile.txt So the quotationmarks irritate me a lot as I can't find a way how to insert my variable values into the command string for the shellcommand as the required format gets destroyed. Another problem is that from what I've seen it also depends on how you execute the shellcommand so I don't know which one is the proper one if I want my script to wait until sed has finished.

Does anyone know how I can do this?

Thanks

CodePudding user response:

You only need quotes if you're executing the command through the shell. When you use subprocess(), you can execute the command directly by passing the command as a list, not a string.

subprocess.run(["sed", "-i", f"s/{orig}/{repl}/g", file_to_edit]);
  • Related