Search code examples
pythonoperating-systemsystempython-3.8

Double quotes inside os.system echo


Here is my code:

import os
os.system("""echo pyklopp init my_model --config="'{\"model\":%s}'" --save "'test_%s/my_model.pth'" """ % ("MODEL", 0))

My output is:

pyklopp init my_model --config='{model:MODEL}' --save 'test_0/my_model.pth'

I want:

pyklopp init my_model --config='{"model":MODEL}' --save 'test_0/my_model.pth'

I want model inside double-quotes as shown above. Any suggestions?

I'm running on Ubuntu.


Solution

  • On Ubuntu you seem to have to double escape the ' and ", like this:

    import os
    os.system("""echo pyklopp init my_model --config=\\'{\\"model\\":%s}\\' --save \\'test_%s/my_model.pth\\' """ % ("MODEL", 0))
    

    Which should give you:

    pyklopp init my_model --config='{"model":MODEL}' --save 'test_0/my_model.pth'
    

    Old answer, for Windows

    Try escaping both ' and ", and remove the double quotes around '{\"model\":%s}\' and 'test_%s/my_model.pth\'.

    Like this:

    import os
    os.system("""echo pyklopp init my_model --config=\'{\"model\":%s}\' --save \'test_%s/my_model.pth\' """ % ("MODEL", 0))
    

    Which gives:

    pyklopp init my_model --config="'{"model":MODEL}'" --save "'test_0/my_model.pth'"
    

    Edit:

    You don't even actually need to escape anything.

    Without escaping:

    import os
    os.system("""echo pyklopp init my_model --config='{"model":%s}' --save 'test_%s/my_model.pth' """ % ("MODEL", 0))
    

    Will give you the same result.