Reputation: 2277
I want to call a python function pexpect.spawn(cmd)
, where cmd is a string as below:
ssh -t [email protected] 'sudo nohup bash -c "./tcp_sender > /dev/null 2>&1 &"'
the ip addresses are always changing, so it is something like:
ssh -t kity@%s 'sudo nohup bash -c "./tcp_sender > /dev/null 2>&1 &"' %host_ip
there are several '
and "
, I'm at a loss how to deal with it
so basically, it is about how to deal with escaping in python strings
and when there is a variable substring, how to deal with it
thanks
Upvotes: 2
Views: 951
Reputation: 365607
Cameron Sparr has already given the general-purpose answer.
But in your specific case, you probably don't need this.
pexpect.spawn
accepts either a command-and-arguments string or a command string and a list of separate argument strings. And the same is true for most similar methods in other libraries (like everything in the standard library subprocess
module).
So, you only need to make each argument into a string, like this:
pexpect.spawn('ssh', ['-t', '[email protected]', 'sudo nohup bash -c "./tcp_sender > /dev/null 2>&1 &"'])
In fact, the documentation specifically suggests this, for exactly this reason:
The second form of spawn (where you pass a list of arguments) is useful in situations where you wish to spawn a command and pass it its own argument list. This can make syntax more clear.
Of course in your case, you're actually spawning a command with a list of arguments… one of which is itself a command to spawn and a list of arguments (sudo
), and so on a few steps down the line (nohup
, bash
, and finally tcp_sender
), and obviously pexpect
can only help with the first of those steps. Fortunately, in this case, that's all you need.
If you do need more, there are some libraries out there that can generate POSIX-style quoted strings out of argument lists (basically the reverse of shlex
), but the few times I've needed one, the one I found turned out to be buggy and I ended up rewriting it myself… It's actually not that complicated (basically, just escape everything then quote all arguments). But hopefully you'll never have to do this.
Upvotes: 0
Reputation: 3981
you could use triple quotes:
"""ssh -t kity@{0} 'sudo nohup bash -c "./tcp_sender > /dev/null 2>&1 &"'""".format(ip_address)
Upvotes: 7