[英]How can I format command arguments which themselves are a group of commands with Python's subprocess module?
Command to run inside MyCWD
(variable capturing working directory): vagrant ssh -c "cd /Path/To/Dir && ./my-shell-script.sh -d argD -f argF"
在MyCWD
内运行的命令(变量捕获工作目录): 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. 后者似乎更容易,但不再推荐使用os.system
。 How can a I get this to work with subprocess.Popen()
? 我怎样才能使用subprocess.Popen()
?
I build out the array ( argCmd
) depending on some settings. 我根据一些设置构建了数组( argCmd
)。 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
. 基本上我构建了这样的数组,然后尝试将它们传递给subprocess.Popen
但是这样奇怪的字符串构建总是让我对那个模块os.system
,但对于os.system
却相当微不足道。 How do you work with strings and subprocess
effectively? 你如何有效地使用字符串和subprocess
?
What you do with your Python code: 你用Python代码做什么:
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'])]
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. 或者像这样的花哨的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.