【问题标题】:python shell subprocess import call invalid syntaxpython shell子进程导入调用无效语法
【发布时间】:2012-12-14 03:28:08
【问题描述】:

我想对目录中的每个文件执行一个 shell 命令。我不断收到错误。

代码如下:

import os
from subprocess import call

for dirname, dirnames, filenames in os.walk('.'):
    for filename in filenames:
        jpg = os.path.join(dirname, filename)
        call(["./curl_recognize.sh", jpg, jpg".txt", "-t txt"])

这是错误:

    call(["./curl_recognize.sh", jpg, jpg".txt", "-t txt"])
                                              ^
SyntaxError: invalid syntax

【问题讨论】:

    标签: python shell call subprocess


    【解决方案1】:

    在“.txt”之前添加一个+。这样就解决了。

    + 运算符在 Python 中连接字符串。当两个字符串都是常量时,您可以将它们彼此相邻放置(“foo” “bar”与“foo bar”相同),但如果其中一个是变量(或任何其他类型的表达式),您必须使用 + 运算符。

    代码中不相关的问题:您可能还需要将“-t txt”更改为“-t”、“txt”,因为前者会将“-t txt”作为单个参数传递给程序,并且几乎所有参数解析程序都期望标志(“-t”)及其值(“txt”)作为单独的参数。

    【讨论】:

    • ./curl_recognize.sh ./whole_foods/wf_cut_bad.JPG ./whole_foods/wf_cut_bad.txt -f txt
    • 或多或少,除非它是“wf_cut_bad.JPG.txt”。如果您想摆脱“JPG”并将其替换为“txt”,请将jpg + ".txt" 替换为jpg.replace(".jpg", ".txt")
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 2015-07-18
    • 2018-09-22
    • 2017-05-05
    • 1970-01-01
    相关资源
    最近更新 更多