3

Command to run inside MyCWD (variable capturing working directory): vagrant ssh -c "cd /Path/To/Dir && ./my-shell-script.sh -d argD -f argF"

I tried doing this but didn't work:

vagrantCmd = ['vagrant','ssh','-c', 
              'cd', '/Path/To/Dir', '&&', 
              './my-shell-script.sh', '-d', '-argD', '-f', 'argF']

output,error = subprocess.Popen(command, universal_newlines=True,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=MyCWD).communicate()

However, if I do this, it just works:

argCmd = ['cd', '/Path/To/Dir', '&&', 
          './my-shell-script.sh', '-d', '-argD', '-f', 'argF']
os.chdir(MyCWD)
os.system('vagrant ssh -c "%s"' % ' '.join(argCmd))

The latter seems to be a lot easier but os.system is no longer recommended. How can a I get this to work with subprocess.Popen()?

I build out the array (argCmd) depending on some settings. Basically I build out such arrays and then try pass them to subprocess.Popen but such weird string building always has me bang my head with that module, but is rather trivial with os.system. How do you work with strings and subprocess effectively?

PhD
  • 11,202
  • 14
  • 64
  • 112

2 Answers2

2

What you do with your Python code:

vagrant ssh -c cd /Path/To/Dir && ./my-shell-script.sh -d argD -f argF

What you need:

vagrant ssh -c "cd /Path/To/Dir && ./my-shell-script.sh -d argD -f argF"

How to fix it?

vagrantCmd = ['vagrant','ssh','-c', 
          ' '.join(['cd', '/Path/To/Dir', '&&', 
          './my-shell-script.sh', '-d', '-argD', '-f', 'argF'])]
enedil
  • 1,605
  • 4
  • 18
  • 34
0

I'd try something like this:

ok = ['vagrant', 'ssh', '-c']
v = '"{}"'.format 
sub = 'cd /Path/To/Dir && ./my-shell-script.sh -d -argD -f argF'
ok.append(v(pipes.quote(sub)))

and:

subprocess.Popen(ok)

see:

... basically wrappers of escaped escaping. Maybe a decorator? Or something fancy, like that.

jmunsch
  • 22,771
  • 11
  • 93
  • 114