How can one format command arguments that are themselves a group of commands with a Python subprocess module?
Command to run inside MyCWD
(variable to capture 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 much easier, but is os.system
no longer recommended. How can I get this to work with subprocess.Popen()
?
I am creating an array ( argCmd
) depending on some parameters. Basically I create arrays like this and then try to pass them to subprocess.Popen
, but such a weird string construction always gets my head up with this module, but pretty trivial with os.system
. How do you work efficiently with strings and subprocess
?
source to share
What do you do with 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'])]
source to share
I would 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)
cm
- https://docs.python.org/2/library/pipes.html#pipes.quote
- How do I avoid calls to os.system () in Python?
- Inserting a nested bash command in Python
... are basically wrappers of escaped escaping. Maybe a decorator? Or something like that.
source to share