0

再会,

tldr ; 配置读取脚本返回单个字符而不是字符串。

我正在编写一个可以使用 SCPI 命令连接到各种仪器的程序。除此之外,每个仪器都必须以不同的方式初始化,并且应该添加新仪器,因此我制作了一个配置文件,如下所示;

### Digital multimeters ###
[34405A]
init : ["*RST", "*CLS", "CONF:VOLT:DC 20, MAX"]

[34401A]
init : ["*RST", "*CLS", "CONF:VOLT:DC 20, MAX"]

### Power supplies ###
[E3634A]
init : ["*RST", "*CLS", "OUTP OFF", "APPLY:P25V", "OUTP ON"]

[E3640A]
init : ["*RST", "*CLS", "OUTP OFF", "APPLY:P25V", "OUTP ON"]

[E3631A]
init : ["*RST", "*CLS", "OUTP OFF", "APPLY:P25V", "OUTP ON"]

[61602]
init : ["*RST", "*CLS", "OUTP OFF", "OUTP:PROT:CLE", "OUTP:COUP AC", 
"VOLT:AC 230", "FREQ 50", "OUTP ON"]

此外,我尝试读取配置文件;

import configparser as cp

conf = cp.ConfigParser()
print(conf.read("devices.ini"))
print(conf.sections())

conn_dev = ["34405A", "61602"]


for devices in conf.sections():
    for (key, val) in conf.items(devices):
        print(devices + " : " + key + " : " + val)
        for commands in val:
            print(commands)

我期望的是一个命令列表,但它返回单个字符,甚至是引号。小样本;

PPA5530 : init : ["*RST", "*CLS"]
[
"
*
R
S
T
"
,

"
*
C
L
S
"
]

它是如何返回单个字符而不是我定义的命令的?

4

1 回答 1

0

val是一个字符串。当你遍历一个字符串时,你一次得到一个字符。

为什么 Python 应该自动将字符串转换为您想要的任何内容?它不知道你想要什么。

转换为listusing ast.literal_eval

>>> import ast
>>> val = '["*RST", "*CLS"]'
>>> val
'["*RST", "*CLS"]'

>>> values = ast.literal_eval(val)
>>> values
['*RST', '*CLS']

>>> for value in values:
...     print(value)
*RST
*CLS
于 2017-05-03T07:42:40.827 回答