Home > Software engineering >  Running sed command with Python doesn't work as it does in bash? [duplicate]
Running sed command with Python doesn't work as it does in bash? [duplicate]

Time:09-16

I am attempting to execute this command from a Python script:

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

When I run from the bash console, it succeeds.

But when I run with the following code, it does not:

    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

But this file clearly exists, I can find it, etc.

What's the issue? Am I missing something?

I'm on Python 3.9

Thanks!

Eduardo

CodePudding user response:

~ is expanded by the shell, it's not part of the actual pathname. Since you're not using the shell to execute the command, it's not expanded. You can use the Python function os.path.expanduser() to do this.

import os

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

I'm not sure why you're using sed to do this. Python can read and write the file itself. It also looks like you're trying to modify JSON using string operations. It would be better to use json.load() to read the file, modify the data, and then rewrite the file with json.dump().

  • Related