如何格式化命令参数,它们本身是一组带有 Python 子进程模块的命令?
How can I format command arguments which themselves are a group of commands with Python's subprocess module?
命令运行 inside MyCWD
(变量捕获工作目录):
vagrant ssh -c "cd /Path/To/Dir && ./my-shell-script.sh -d argD -f argF"
我尝试这样做但没有成功:
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()
但是,如果我这样做,它就会起作用:
argCmd = ['cd', '/Path/To/Dir', '&&',
'./my-shell-script.sh', '-d', '-argD', '-f', 'argF']
os.chdir(MyCWD)
os.system('vagrant ssh -c "%s"' % ' '.join(argCmd))
后者似乎容易但os.system
不再推荐。我怎样才能让它与 subprocess.Popen()
一起工作?
我根据一些设置构建数组 (argCmd
)。基本上我构建了这样的数组,然后尝试将它们传递给 subprocess.Popen
,但是这种奇怪的字符串构建总是让我对那个模块感到头疼,但对 os.system
来说却微不足道。您如何有效地使用字符串和 subprocess
?
我会尝试这样的事情:
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)))
和:
subprocess.Popen(ok)
见:
- https://docs.python.org/2/library/pipes.html#pipes.quote
- How to escape os.system() calls in Python?
- Putting nested bash command in Python
...基本上是转义的包装器。也许是装饰师?或者像那样的花哨的东西。
您使用 Python 代码做什么:
vagrant ssh -c cd /Path/To/Dir && ./my-shell-script.sh -d argD -f argF
你需要什么:
vagrant ssh -c "cd /Path/To/Dir && ./my-shell-script.sh -d argD -f argF"
如何解决?
vagrantCmd = ['vagrant','ssh','-c',
' '.join(['cd', '/Path/To/Dir', '&&',
'./my-shell-script.sh', '-d', '-argD', '-f', 'argF'])]
命令运行 inside MyCWD
(变量捕获工作目录):
vagrant ssh -c "cd /Path/To/Dir && ./my-shell-script.sh -d argD -f argF"
我尝试这样做但没有成功:
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()
但是,如果我这样做,它就会起作用:
argCmd = ['cd', '/Path/To/Dir', '&&',
'./my-shell-script.sh', '-d', '-argD', '-f', 'argF']
os.chdir(MyCWD)
os.system('vagrant ssh -c "%s"' % ' '.join(argCmd))
后者似乎容易但os.system
不再推荐。我怎样才能让它与 subprocess.Popen()
一起工作?
我根据一些设置构建数组 (argCmd
)。基本上我构建了这样的数组,然后尝试将它们传递给 subprocess.Popen
,但是这种奇怪的字符串构建总是让我对那个模块感到头疼,但对 os.system
来说却微不足道。您如何有效地使用字符串和 subprocess
?
我会尝试这样的事情:
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)))
和:
subprocess.Popen(ok)
见:
- https://docs.python.org/2/library/pipes.html#pipes.quote
- How to escape os.system() calls in Python?
- Putting nested bash command in Python
...基本上是转义的包装器。也许是装饰师?或者像那样的花哨的东西。
您使用 Python 代码做什么:
vagrant ssh -c cd /Path/To/Dir && ./my-shell-script.sh -d argD -f argF
你需要什么:
vagrant ssh -c "cd /Path/To/Dir && ./my-shell-script.sh -d argD -f argF"
如何解决?
vagrantCmd = ['vagrant','ssh','-c',
' '.join(['cd', '/Path/To/Dir', '&&',
'./my-shell-script.sh', '-d', '-argD', '-f', 'argF'])]