0

Possible Duplicate:
Python module to shellquote/unshellquote?

I am trying to pass a string's value into a command as input, in Python for executing a bash command. I currently have somthing like this:

cmd = 'echo ' + <StringValue> + ' | command'
output = commands.getOutput(cmd)

but it does not work because my string value also contains both " and ', so it parses them wrong. Can anyone please tell me how I can pass this?

Community
  • 1
  • 1
laviniap
  • 1
  • 1
  • Could you supplement your example with a concrete example of what you are trying to do and the resulting error message? I was able to get the following to at run: `string_input = "bbbb 'aaaa'"; commands.getoutput('echo %s; ls ' % string_input)` – dtlussier Dec 07 '11 at 18:24
  • using `subprocess.call` and passing a stdin parameter is almost certainly better than making a system call to echo followed by a pipe. – Wooble Dec 07 '11 at 18:24

2 Answers2

0

The commands module is currently deprecated since python 2.6 and removed in python 3, you should use the subprocess module instead.

The replacing shell pipeline section in the python documentation should provide the information you need.

Edit: As a follow-up to your comment question, you could use the following code to pass a string to your process:

import subprocess

process = subprocess.Popen('cat', stdin=subprocess.PIPE)
process.stdin.write('abc "def"')
process.communicate()

The output this would be abc "def" with the quotes as you're looking for.

jcollado
  • 39,419
  • 8
  • 102
  • 133
  • The problem with echo is the following: echo "abc "def"" abc def. As you can see, the " that surround def have disappeared from the output. I would use subprocess, but I don't want to use a file as stdin. How can I use stdin and pass it a string? – laviniap Dec 07 '11 at 18:28
  • Use a StringIO object instead of a real file. – Wooble Dec 07 '11 at 18:31
0

As for the parsing, you can use triple quotes to have literal " and ' in a string:

>>> print """test "a" 'b'"""
test "a" 'b'
silvado
  • 17,202
  • 2
  • 30
  • 46