Hühnerbrust
Hühnerbrust

Reputation: 63

How to open a file with xdg-open in a python script? (wrong application used)

I am trying to open a file on an Ubuntu machine from within Python script. However, xdg-open will always use another application (the wrong one) when started from the python script, while it will use the correct one when started from the shell.

I tried with the following commands:

subprocess.Popen([f"xdg-open {file_path}"])
subprocess.Popen([f"xdg-open {file_path}"], user="user", env=os.environ, shell=True)

Any idea, what to do?

[EDIT] Additional Information:

file_path is the full path to the file like "/tmp/file.odt". The file is actually there, because it is opened.

The file is a libreoffice writer file that ends with odt.

If I open the file with "xdg-open /tmp/file.opt" in a shell, it opens in libreoffice writer, as expected.

If I open the file via the python script, it opens the file in the ebook-viewer application that I have installed in my ubuntu.

I use subprocess.popen instead of run because I open the file in an async function and want the script to continue and not wait for the file to be closed. I read that in such cases you need to use popen. However, I am new to this and would switch to run if it would help. However, I tested subprocess.run and had the same result as described above.

Generally, the script is used to open a websocket server listen for a request that provides the file, store the file in the tmp directory, and then open it. Everything works, but the wrong application is used for opening the file...

Thanks!

Upvotes: 0

Views: 38

Answers (1)

Hühnerbrust
Hühnerbrust

Reputation: 63

Solved it. The problem is that using subprocess.run or subprocess.Popen the xdg-open command uses the information from the /usr/share/applications/mimeinfo.cache file.

This file is rebuilt on every boot of ubuntu.

In addition, callibre ebook reader had the libreoffice text mime types included in the respective .desktop files.

By removing libreoffice text mime types from the .desktop files and rebuilding the mimeinfo.cache file, I solved it.

The question remains: Why does xdg-open use this information when started with subprocess.Popen and not when started via the shell...

Upvotes: 0

Related Questions