[Tutor] Open a libreoffice calc file in Python
cs at zip.com.au
cs at zip.com.au
Wed Dec 21 23:50:13 EST 2016
On 21Dec2016 21:54, boB Stepp <robertvstepp at gmail.com> wrote:
>On Wed, Dec 21, 2016 at 9:37 PM, Jim Byrnes <jf_byrnes at comcast.net> wrote:
>> Python 3.4 on Ubuntu
>> If I was going to open a libreoffice calc file from the terminal I would go:
>> libreoffice --calc /home/path/to/myfile.ods.
>>
>> How would I do this from Python?
>
>My first thought was:
>
>import os
>os.system(insert_your_command)
>
>But looking at the documentation
>(https://docs.python.org/3/library/os.html#os.system) it says it is
>preferable to use the subprocess module with documentation here:
>https://docs.python.org/3/library/subprocess.html#replacing-os-system
>
>It makes me wonder if I should go back and revisit some code I wrote
>as I used the os.system()approach. But was this option available in
>Py 2.4.4? I'll have to check.
Subprocess arrived with Python 2.4, so you should be fine.
To my mind the more important thing is to use the "shell=False" version of
Popen. os.system() inherently accepts a shell command string, which means you
need to hand quote the /home/path/to/myfile.ods. But it is better to pass an
array of strings:
['libreoffice', '--calc', path_value]
where path_value is a Python variable containing "/home/path/to/myfile.ods" or
whatever the path is. This way you don't need to do anything special for, um,
"unusual" paths because you're not passing the string _through_ the shell.
BTW, the array form is Popen's default mode; sensibly you need to _ask_ to use
a shell string with shell=True, because that is harder and more fragile.
Cheers,
Cameron Simpson <cs at zip.com.au>
More information about the Tutor
mailing list