-1

When I run the same command in a bash script it works. When I want to pass it to shell through Python's os.system it complains because of the {and: characters.

import os
os.system('composer transaction submit -c admin@tutorial-network -d '{"$class": "org.acme.frame.auction.SetupDemo1"}'')


Shell Error:
os.system('composer transaction submit -c admin@tutorial-network -d '{"$class": "org.acme.frame.auction.SetupDemo1"}'')
                                                                         ^
SyntaxError: invalid syntax
Klaus D.
  • 13,874
  • 5
  • 41
  • 48
Nima Afraz
  • 36
  • 5
  • You have troubles with the quotation. The best and recommended solution would be to use the [subprocess](https://docs.python.org/3/library/subprocess.html) module instead of `os.system()` and hand in the arguments as a list. See the examples in the link. – Klaus D. Jan 27 '19 at 12:19
  • 1
    `os.system("""composer transaction submit -c admin@tutorial-network -d '{"$class": "org.acme.fram e.auction.SetupDemo1"}'""")` – Alex Python Jan 27 '19 at 12:20
  • @KlausD. I have tried subprocess as well, The same syntax error. – Nima Afraz Jan 27 '19 at 12:21
  • @AlexPython Perfect, Problem Solved. Thanks. Now, How would I pass a variable into this string without messing up the quotation? os.system("""composer transaction submit -c admin@tutorial-network -d '{"$class": "org.acme.frame.auction.Offer", "bidPrice": %variable_x, "listing": "resource:org.acme.frame.auction.FrameListing#0001", "member": "resource:org.acme.frame.auction.Member#VNO2"}'""") this does not work. – Nima Afraz Jan 27 '19 at 12:29
  • @NimaAfraz use % formatting operator or construct your system cmd string by parts; also look at `subprocess` to make your life easier – Alex Python Jan 27 '19 at 12:33
  • If the same happened with `subprocess` you did not use it properly. – Klaus D. Jan 27 '19 at 12:53
  • You cannot have googled these questions. My top google hit for your follow-up question is https://stackoverflow.com/questions/3542714/variable-interpolation-in-python – tripleee Jan 27 '19 at 13:44

1 Answers1

2

You cannot nest single quotes. The string which starts with os.system(' ends at the next (unescaped) single quote.

Python offers triple quotes which provide for a trivial fix:

os.system(r"""composer transaction submit -c admin@tutorial-network -d '{"$class": "org.acme.frame.auction.SetupDemo1"}'""")

A better solution altogether is to use subprocess.run without shell=True so you don't have to understand both Python's and the shell's quoting mechanisms.

subprocess.run([
        'composer', 'transaction',
        'submit', '-c', 'admin@tutorial-network',
        '-d', '{"$class": "org.acme.frame.auction.SetupDemo1"}'],
    # probably a good idea
    check=True)

For (much) more on this topic, see further https://stackoverflow.com/a/51950538/874188

tripleee
  • 175,061
  • 34
  • 275
  • 318