Python 切换配置文件设置的好方法是什么?

Python 切换配置文件设置的好方法是什么?,python,bash,configuration,Python,Bash,Configuration,我想通过命令行修改一些配置设置,例如sshd\u config的UsePAM。“问题”在于,根据系统的不同,现有配置文件要么只有一个设置为yes或no的条目,要么两行都有,但其中一行被注释掉,或者依赖默认值,该设置尚不存在。当然,我可以简单地 sed -i '/^.*UsePAM/d;' /etc/sshd_config # remove all occurrences so far echo "UsePAM yes" >> /etc/sshd_config # append

我想通过命令行修改一些配置设置,例如
sshd\u config
UsePAM
。“问题”在于,根据系统的不同,现有配置文件要么只有一个设置为
yes
no
的条目,要么两行都有,但其中一行被注释掉,或者依赖默认值,该设置尚不存在。当然,我可以简单地

sed -i '/^.*UsePAM/d;' /etc/sshd_config  # remove all occurrences so far
echo "UsePAM yes" >> /etc/sshd_config    # append the new value to the end
(只要不涉及任何部分),但这是相当次优的。我可以编写一个小型Python程序来手动实现该算法

if setting not present:
    append it to the correct section
elif setting present both commented and not:
    swap commenting if necessary
else:
    set/uncomment the single occurrence of the setting

但是有没有更简单的方法呢?

使用sed/echo而不是
sed/echo
@J.F.Sebastian谢谢,我来看看!