简体   繁体   中英

Running python in subprocess.call(cmd, ...) get error with message /bin/sh: -c: line 0: syntax error near unexpected token `('

My code (python3 run in virtualenv )

 try:
    cmd = "cd NST/experiments && python main.py eval  --model models/21styles.model --content-image " + directory + "/" + filename + " --style-image " + STYLE_IMAGE_UPLOAD + "wikiart/" + choose_file() + " --output-image " + OUTPUT_IMAGE_UPLOAD + filename + " --content-size 600" " --cuda=0"
    returned_value = subprocess.call(cmd, shell=True)  # returns the exit code in unix
    print('returned value:', returned_value)

  except Exception as e:
    print(e)

I got this error during run the script

/bin/sh: -c: line 0: syntax error near unexpected token `('
/bin/sh: -c: line 0: `cd NST/experiments && python main.py eval  --model models/21styles.model --content-image /Users/kanel/Documents/Developments/ML/applications/static/nst/content_image/en_20191208/20.jpg --style-image /Users/kanel/Documents/Developments/ML/applications/static/nst/style_image/wikiart/facsimile-of-may-courtly-figures-on-horseback(1).jpg --output-image /Users/kanel/Documents/Developments/ML/applications/static/nst/output_image/20.jpg --content-size 600 --cuda=0'

You have unquoted strings in the command line. In general, it is nice to have any passed values/variables to system calls (or subprocess or etc) quoted by default or it is possible to get bugs like you have now.

I've a bit restructured your source code, added quoting and did it added more readability to the source code block.

Here is the code which should work for you well :)

try:
    from pipes import quote as quote_path
except ImportError:
    from shlex import quote as quote_path

try:
    cmd = (
        "cd NST/experiments && python main.py eval  --model models/21styles.model "
        "--content-image {} "
        "--style-image {} "
        "--output-image {} "
        "--content-size 600 --cuda=0"
    ).format(
        quote_path(directory + " / " + filename),
        quote_path(STYLE_IMAGE_UPLOAD + "    wikiart / " + choose_file()),
        quote_path(OUTPUT_IMAGE_UPLOAD + filename)
    )
    returned_value = subprocess.call(cmd, shell=True)  # returns the exit code in unix
    print('returned value:', returned_value)

except Exception as e:
    print(e)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM