- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想在 python3 中使用 subprocess.Popen()
运行以下 jq
命令。
$ jq 'INDEX(.images[]; .id) as $imgs | {
"filename_with_label":[
.annotations[]
| select(.attributes.type=="letter" )
| $imgs[.image_id] + {label:.text}
| {id:.id} + {filename:.file_name} + {label:.label}
]
}' image_data_annotation.json > image_data_annotation_with_label.json
请注意,第一个命令行参数包含点、美元符号、单引号内的双引号。仅供引用,jq
是用于处理 json 文件的 JSON 处理器实用程序。
我编写了以下 python3 脚本,用于使用 jq
实用程序自动处理 JSON 文件。
#!python3
# file name: letter_image_tool.py
import os, subprocess
"""
command line example to automate
$ jq 'INDEX(.images[]; .id) as $imgs | {
"filename_with_label":[
.annotations[]
| select(.attributes.type=="letter" )
| $imgs[.image_id] + {label:.text}
| {id:.id} + {filename:.file_name} + {label:.label}
]
}' image_data_annotation.json > image_data_annotation_with_label.json
"""
# define first command line argument
jq_filter='\'INDEX(.images[]; .id) as $imgs | { "filename_with_label" : [ .annotations[] | select(.attributes.type=="letter" ) | $imgs[.image_id] + {label:.text} | {id:.id} + {filename:.file_name} + {label:.label} ] }\''
input_json_files= [ "image_data_annotation.json"]
output_json_files= []
for input_json in input_json_files:
print("Processing %s" %(input_json))
filename, ext = os.path.splitext(input_json)
output_json = filename + "_with_label" + ext
output_json_files.append(output_json)
print("output file is : %s" %(output_json))
#jq_command ='jq' + " " + jq_filter, input_json + ' > ' + output_json
jq_command =['jq', jq_filter, input_json + ' > ' + output_json]
print(jq_command)
subprocess.Popen(jq_command, shell=True)
在 bash 上运行上述 python 脚本会产生以下结果:
$ ./letter_image_tool.py
Processing image_data_annotation.json
output file is : image_data_annotation_with_label.json
['jq', '\'INDEX(.images[]; .id) as $imgs | { "filename_with_label" : [ .annotations[] | select(.attributes.type=="letter" ) | $imgs[.image_id] + {label:.text} | {id:.id} + {filename:.file_name} + {label:.label} ] }\'', 'image_data_annotation.json > image_data_annotation_with_label.json']
jq - commandline JSON processor [version 1.6-124-gccc79e5-dirty]
Usage: jq [options] <jq filter> [file...]
jq [options] --args <jq filter> [strings...]
jq [options] --jsonargs <jq filter> [JSON_TEXTS...]
jq is a tool for processing JSON inputs, applying the given filter to
its JSON text inputs and producing the filter's results as JSON on
standard output.
The simplest filter is ., which copies jq's input to its output
unmodified (except for formatting, but note that IEEE754 is used
for number representation internally, with all that that implies).
For more advanced filters see the jq(1) manpage ("man jq")
and/or https://stedolan.github.io/jq
Example:
$ echo '{"foo": 0}' | jq .
{
"foo": 0
}
For a listing of options, use jq --help.
它不处理 jq
实用程序的第一个参数:
'INDEX(.images[]; .id) as $imgs | {
"filename_with_label":[
.annotations[]
| select(.attributes.type=="letter" )
| $imgs[.image_id] + {label:.text}
| {id:.id} + {filename:.file_name} + {label:.label}
]
}'
第一个参数应该像上面的片段一样用单引号括起来,但我的脚本不处理它。
我认为主要问题与第一个命令行参数(上述 python 脚本中的 jq_filter
)中使用的点、美元符号、单引号和双引号有关。但是我不知道如何处理这种与 bash 相关的复杂元字符。
如何解决以上问题?
感谢您的阅读。
更新我的解决方案
jq_filter 定义用三重引号,空格分隔连接如下
#!python3
# file name: letter_image_tool.py
import os, subprocess
"""
command line example to automate
$ jq 'INDEX(.images[]; .id) as $imgs | {
"filename_with_label":[
.annotations[]
| select(.attributes.type=="letter" )
| $imgs[.image_id] + {label:.text}
| {id:.id} + {filename:.file_name} + {label:.label}
]
}' image_data_annotation.json > image_data_annotation_with_label.json
"""
# define first command line argument with triple quotes
jq_filter=""" 'INDEX(.images[]; .id) as $imgs | {
"filename_with_label" : [
.annotations[]
| select(.attributes.type=="letter" )
| $imgs[.image_id] + {label:.text}
| {id:.id} + {filename:.file_name} + {label:.label} ] } ' """
input_json_files= [ "image_data_annotation.json"]
output_json_files= []
for input_json in input_json_files:
print("Processing %s" %(input_json))
filename, ext = os.path.splitext(input_json)
output_json = filename + "_with_label" + ext
output_json_files.append(output_json)
print("output file is : %s" %(output_json))
#jq_command ='jq' + " " + jq_filter, input_json + ' > ' + output_json
# jq command composed with space separated join
jq_command =' '.join['jq', jq_filter, input_json, ' > ', output_json]
print(jq_command)
# shell keyword argument should be set True
subprocess.Popen(jq_command, shell=True)
使用三重双引号,jq_filter 可以使用多行定义而不是单行定义更具可读性。
最佳答案
您需要单引号的原因是为了防止 shell 对您的参数进行任何扩展。这是一个问题,只有在使用 shell=True
时才会出现。如果未设置,shell 将永远不会触及您的参数,也无需“保护”它们。
但是,shell 还负责 stdout
重定向(即 [... '>', output_json]
)。不使用 shell,需要在 Python 代码中处理重定向。然而,这就像将参数 stdout=...
添加到 Popen
一样简单。
总而言之,这意味着您的代码可以重写为
import os
import subprocess
# Still define first command line argument with triple quotes for readability
# Note that there are no single quotes though
jq_filter = """INDEX(.images[]; .id) as $imgs | {
"filename_with_label" : [
.annotations[]
| select(.attributes.type=="letter" )
| $imgs[.image_id] + {label:.text}
| {id:.id} + {filename:.file_name} + {label:.label} ] }"""
input_json_files = ["image_data_annotation.json"]
output_json_files = []
for input_json in input_json_files:
print("Processing %s" % (input_json))
filename, ext = os.path.splitext(input_json)
output_json = filename + "_with_label" + ext
output_json_files.append(output_json)
print("output file is : %s" % (output_json))
# Keep command as list, since this is what we need when NOT using shell=True
# Note also that the redirect and the output file are not parts of the argument list
jq_command = ['jq', jq_filter, input_json]
# shell keyword argument should NOT be set True
# Instead redirect stdout to an out_file
# (We must open the file for writing before redirecting)
with open(output_json, "w") as out_file:
subprocess.Popen(jq_command, stdout=out_file)
通常建议无论如何不要使用 shell=True
,因为这会打开另一个针对代码的攻击向量,因为注入(inject)攻击可以提供对 shell 的完全访问权限。此外,不使用 shell 的另一个小好处是它将减少创建的子进程的数量,因为不需要额外的 shell 进程。
关于python - 如何将 popen 与命令行参数一起使用包含单引号和双引号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61182346/
在线编写 yacc 代码的教程使用单引号表示分号和其他字符: ';' '+' '-' (etc) 但是在使用时: '' 在我将其更改为双引号之前,我遇到了错误: "" 相似地, '>=' '==
MySQL documentation说它应该是\'。然而,scite 和 mysql 都显示 '' 有效。我看到了,它有效。我该怎么办? 最佳答案 您引用的 MySQL 文档实际上比您提到的要多一些
MySQL documentation说它应该是\'。然而,scite 和 mysql 都显示 '' 有效。我看到了,它有效。我该怎么办? 最佳答案 您引用的 MySQL 文档实际上比您提到的要多一些
MySQL documentation说它应该是\'。然而,scite 和 mysql 都显示 '' 有效。我看到了,它有效。我该怎么办? 最佳答案 您引用的 MySQL 文档实际上比您提到的要多一些
MySQL documentation说它应该是\'。然而,scite 和 mysql 都显示 '' 有效。我看到了,它有效。我该怎么办? 最佳答案 您引用的 MySQL 文档实际上比您提到的要多一些
我一直在使用 SED (Bash shell) 转义单引号问题。 我需要做 $cfg['Servers'][$i]['password'] = ''; 进入 $cfg['Servers'][$i]['
需要将'替换为\'但这就是我得到的: >>> s = "It's nice to have an example" >>> s.replace("'", "\\'") "It\\'s nice to
我在处理连接字符串中的 ' 字符时遇到问题。 Entity Framework 抛出异常说: Format of the initialization string does not conform
我遇到了一个非常奇怪的问题,我无法设置 Content-Security-Policy 所需的单引号。我假设我运行的是旧版本的 ingress,它仅在我禁用并重新启用它 (microk8s) 后才得到
插入带有撇号的值的正确 SQL 语法是什么? Insert into Person (First, Last) Values 'Joe', 'O'Brien' 我不断收到错误,因为我认为
我有三列数据 selector label option list time you personally
我使用 Java Pattern 类将正则表达式指定为字符串。 举个例子我喜欢成为蜘蛛侠:“彼得·帕克” 应将蜘蛛侠和“Peter Parker”列为单独的标记。谢谢 try { Buffe
我正在尝试删除标记 ' (单引号)但我不知道如何。 我在做delm \'但它不起作用。我也尝试了我能想到的所有组合。 我意识到这更像是一个 Vim 脚本问题,但我在任何地方都找不到。 最佳答案 为什么
如何禁用红色突出显示的特定实例。 我尝试在单引号前输入转义符,但没有成功。我确信单引号导致了红色突出显示,因为当我删除它时,它就会消失。 代码如下: import React from 'react'
我需要输出单引号 (')。它必须是单引号而不是 ',因为这是用于向 jquery 函数提供数据的字符串的一部分。 我使用 C# 循环遍历一个对象来构建一个字符串 "var data = [['Item
我正在尝试: "l'ape"); ?> var my_javascript_object = jQuery.parseJSON(''); 我收到此错误“未捕获的语法错误:意外的标识符”。问题是
我的问题是关于传递给方法验证的“add\”反斜杠单引号,该反斜杠单代码有什么用? document.writeln('\',\'N\'))>'); 最佳答案 欢迎来到堆栈溢出。 反斜杠告诉代码这不是引
我要执行命令: xcodebuild -exportArchive -exportFormat IPA -archivePath myApp.xcarchive -exportPath myApp.i
我有一个字符串,里面有一个 ': example link text 不幸的是,这似乎不起作用。 Firebug 提示“SyntaxError:参数列表后缺少 )”,您可以看到 HTML 实体已被 '
据我所知,'mars%22%3A%22' 和 "mars%22%3A%22" 是等效的,因为没有任何内容被转义. 我创建 javscript 书签已经有一段时间了。有一次,当按原样粘贴到 Chrome
我是一名优秀的程序员,十分优秀!