1

I have a command in python:

os.system('echo {{"value": {0:0.0f}}} | /usr/bin/cmd -parameters'.format(value)) 

the thing is that I receive value instead of "value". I would like to have "value" in shell. I've tried with triple double quotes, with slashes and json.dumps. Nothing helped, still value instead of "value".

Could you help me?

4
  • use subprocess so the quoting is handled for you Commented Sep 3, 2018 at 12:12
  • Try using subprocess.call docs.python.org/2/library/… this gives much better results. Commented Sep 3, 2018 at 12:12
  • @molbdnilo That's not related to the issue, that's only due to him not giving example of what value is. The string format is a dead give away of your issue. The missing quotes in output issue is not related to that. Commented Sep 3, 2018 at 12:15
  • @ThePjot Oh, yes. Of course. Commented Sep 3, 2018 at 12:22

2 Answers 2

2

os.system is deprecated. Use subprocess instead, which will handle the quoting nicely for you.

Since you have a pipe, you would normally have to create 2 subprocess objects, but here you just want to feed standard input so:

import subprocess p = subprocess.Popen(["/usr/bin/cmd","-parameters"],stdin=subprocess.PIPE) p.communicate('{{"value": {:0.0f}}}\n'.format(value).encode()) # we need to provide bytes rc = p.wait() 

The quoting issue is gone, since you're not using a system command to provide the argument, but pure python.

to test this I have changed the command to more so I can run it on windows (which also proves that this is portable):

import subprocess value=12.0 p = subprocess.Popen(["more.com"],stdin=subprocess.PIPE) p.communicate('{{"value": {:0.0f}}}\n'.format(value).encode()) rc = p.wait() 

that prints: {"value": 12}

Sign up to request clarification or add additional context in comments.

5 Comments

This does not work, value is still unquoted in the output. You need to escape the double quotes around value
Which python version are you using. For me it outputs {value: 12} on mac with python 3.7.0
python 3.4. But you need .encode() for it to work (the first time I had forgotten it). Have you tried the "more" example without any changes?
Yeah, I already added the encode, but nevermind, the problem was on my site. Have your upvote.
I'm relieved. Thanks
1

If you want to echo quotes, you need to escape them.

For example:

echo "value" 

value

echo "\"value\"" 

"value"

So your python code should look like

os.system('echo {{\\"value\\": {0:0.0f}}} | /usr/bin/cmd -parameters'.format(value)) 

Note, that you should use double slashes \\ because python would escape a single slash.

2 Comments

Correct, but not for os.system. Does not work on linux for example. >>> os.system('echo {{"\"value\"": {0:0.0f}}}'.format(3)) {value: 3}
You are right, I updated my answer. You should use double slashes

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.