subprocess Popen用ssh拆分参数

时间:2014-12-03 08:18:01

标签: python python-2.6

当我尝试使用subprocess.Popen在ssh上执行命令时,包含空格的参数被拆分为多个参数。我究竟做错了什么?我如何解决这个问题,以便远程脚本正确引用参数?

代码:

#!/usr/bin/python2.6
import sys
import subprocess

print "\n ### Starting test.py ###"
print "sys.argv:", sys.argv

if "--exit" in sys.argv:
    print "Bye..."
    sys.exit(1)

# Create command
full_cmd = ["ssh", "localhost"]
full_cmd.append("/home/moberg/tmp/test.py")
full_cmd.extend(sys.argv[1:])
full_cmd.append("--exit")

print "full_cmd:", full_cmd

prog = subprocess.Popen(full_cmd)
prog.communicate()
sys.exit(prog.returncode)

输出:

./test.py -p --act="hej hej"

 ### Starting test.py ###
sys.argv: ['./test.py', '-p', '--act=hej hej']
full_cmd: ['ssh', 'localhost', '/home/moberg/tmp/test.py', '-p', '--act=hej hej', '--exit']

 ### Starting test.py ###
sys.argv: ['/home/moberg/tmp/test.py', '-p', '--act=hej', 'hej', '--exit']
Bye...

预期输出为sys.argv: ['/home/moberg/tmp/test.py', '-p', '--act=hej hej', '--exit']

澄清:只有在命令中使用ssh时才会发生这种情况。删除" ssh"," localhost"从cmd和论点保持完整;输出是我所期望的:

./test.py -p --act="hej hej"

 ### Starting test.py ###
sys.argv: ['./test.py', '-p', '--act=hej hej']
full_cmd: ['/home/moberg/tmp/test.py', '-p', '--act=hej hej', '--exit']

 ### Starting test.py ###
sys.argv: ['/home/moberg/tmp/test.py', '-p', '--act=hej hej', '--exit']
Bye...

0 个答案:

没有答案