Search code examples
pythonpython-3.xlinuxsubprocesspython-os

Open and display a file within a python script in Linux


I'd like to open/display an excel file that I'm saving as part of python processing within the python script.

The save portion of the code works fine (ie, it saves successfully, and I'm open and view from a Nautilus window), but attempting to open programmatically throws errors no matter how I attempt it.

I've been using the Popen method within the subprocess package:

from subprocess import Popen
Popen('./temp/testtest.xlsx')

Gives:

PermissionError: [Errno 13] Permission denied: './temp/testtest.xlsx'

I subsequently tried changing file permissions:

import os
from subprocess import Popen

os.chmod('./temp/testtest.xlsx',0o777)
Popen('./temp/testtest.xlsx')

Which gave:

Out[127]: <subprocess.Popen at 0x7faeb22a4b00>invalid file (bad magic number): Exec format error

And against better judgement tried running as shell:

from subprocess import Popen
Popen('./temp/testtest.xlsx', shell=True)

Which gave:

invalid file (bad magic number): Exec format error 
Out[129]: <subprocess.Popen at 0x7faeb22a46a0>

I also tried it with the file saved in a different directory with similar errors. If it matters, I'm using the openpyxl module to create and save the excel file, but I have the same issues even if it's an excel file I created manually.


Solution

  • The argument to Popen() needs to be a shell command to open the file. If you're using LibreOffice, the program is localc; if you're using OpenOffice it's oocalc.

    from subprocess import Popen
    import os
    f = os.path.join('temp', filename)
    Popen(['localc', f])