运行 使用 Python 的 sed 命令不能像在 bash 中那样工作?

Running sed command with Python doesn't work as it does in bash?

我正在尝试从 Python 脚本执行此命令:

sed -i s/"exited_cleanly":false/"exited_cleanly":true/ ~/.config/chromium/Default/Preferences

当我从 bash 控制台 运行 时,它成功了。

但是当我运行用下面的代码时,它没有:

    process = subprocess.Popen(['sed', '-i', 's/"exited_cleanly":false/"exited_cleanly":true/', '~/.config/chromium/Default/Preferences'], stdout=subprocess.PIPE)
    process.communicate()

    >>> sed: can't read ~/.config/chromium/Default/Preferences: No such file or directory

但是这个文件明明是存在的,我能找到它等等

有什么问题?我错过了什么吗?

我在 Python 3.9

谢谢!

爱德华多

~ 由 shell 扩展,它不是实际路径名的一部分。由于您没有使用 shell 来执行命令,因此它没有展开。您可以使用 Python 函数 os.path.expanduser() 来执行此操作。

import os

process = subprocess.Popen(['sed', '-i', 's/"exited_cleanly":false/"exited_cleanly":true/', os.path.expanduser('~/.config/chromium/Default/Preferences')], stdout=subprocess.PIPE)

我不确定您为什么要使用 sed 来执行此操作。 Python 可以读写文件本身。看起来您也在尝试使用字符串操作修改 JSON 。最好用json.load()读取文件,修改数据,然后用json.dump()重写文件。