-1

Is their any way that i can pass variable value of python to my unix command

Note : var is a python variable which stores filename with path

var='/d/demo/f/f.txt'

Want to call var to my sed command

os.system(bash -c 'sed -i "1i\NAME" var ')

This throws me error at "1i\" syntax invalid

  • BTW, `os.system("something")` runs `sh -c "something"`, so `os.system("bash -c something")` is running `sh -c "bash -c something"` -- two shells when you might not even need one. – Charles Duffy Oct 11 '21 at 16:05

1 Answers1

0

Use subprocess.run, not os.system(), and pass an array of individual argument-vector entries.

var = '/d/demo/f/f.txt'
subprocess.run(['sed', '-i', r'1i\NAME', var])

Each argument needs to be escaped according to Python rules, not shell rules; hence using r'1i\NAME' for a string with a literal backslash in it. You could also achieve the same effect with '1i\\NAME'.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441