在subprocess.call(cmd,…)中运行python get error with message/bin/sh:c:第0行:意外标记“(”附近的语法错误

2024-10-03 09:17:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码(python3在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)

我在运行脚本时遇到了这个错误

/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'

Tags: imageoutputmodelvaluestylestaticcontentml
1条回答
网友
1楼 · 发布于 2024-10-03 09:17:16

命令行中有未加引号的字符串。一般来说,默认引用任何传递给系统调用(或子进程等)的值/变量都是很好的,否则可能会出现像现在这样的bug

我对你的源代码进行了一点重构,添加了引号,并为源代码块增加了可读性

以下代码应该对您很有用:)

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)

相关问题 更多 >