Seite 1 von 1

Question regarding os.system

Verfasst: Montag 21. Dezember 2015, 00:14
von mfkfx
Hello,

I have a problem combining convert with Pythons os.system:

os.system("convert -pointsize 20 -fill yellow -draw "text 270,460 '$(date)'" image_tmp.jpg image.jpg")


Code: Select all

Code: Alles auswählen

os.system("convert -pointsize 20 -fill yellow -draw "text 270,460 '$(date)'" image_tmp.jpg image.jpg")
                                                            ^
SyntaxError: invalid syntax


I think the reason is the amount of "" used in this line.

Can anyone help me with this?

Regards

Re: Question regarding os.system

Verfasst: Montag 21. Dezember 2015, 07:28
von mutetella
@mfkfx
`os.system` is deprecated since Python 2.6. If you must use it, escape the quotation marks:

Code: Alles auswählen

os.system("convert -pointsize 20 -fill yellow -draw \"text 270,406 '$(date)'\" image_tmp.jpg image.jpg")
Otherwise do it with the subprocess module:

Code: Alles auswählen

>>> date = subprocess.Popen(['date'], stdout=subprocess.PIPE).communicate()[0].strip()
>>> args = ['convert', '-pointsize', '20', '-fill', 'yellow', '-draw', 'text 270,460 "{}"'.format(date), 'image_tmp.jpg', 'image.jpg']
>>> subprocess.call(args)

Re: Question regarding os.system

Verfasst: Montag 21. Dezember 2015, 11:25
von Sirius3
and since Python has built in datetime formatting, you don't have to rely on an external program:

Code: Alles auswählen

import datetime
import subprocess
text = 'text 270,460 "{:%a %d %b %Y %H:%M:%S}"'.format(datetime.datetime.now())
subprocess.call(['convert', '-pointsize', '20', '-fill', 'yellow', '-draw', text, 'image_tmp.jpg', 'image.jpg'])

Re: Question regarding os.system

Verfasst: Montag 21. Dezember 2015, 13:13
von BlackJack
ImageMagick also has direct Python bindings for the shared libary (`libmagick++`). Install the bindings and you don't have to call external programs at all:

Code: Alles auswählen

#!/usr/bin/env python
# coding: utf-8
from __future__ import absolute_import, division, print_function
from datetime import datetime as DateTime
from PythonMagick import Image, DrawableText


def main():  
    image = Image('image_tmp.jpg')
    image.fontPointsize(20)
    image.fillColor('yellow')
    image.draw(
        DrawableText(270, 460, format(DateTime.now(), '%a %d %b %Y %H:%M:%S'))
    )
    image.write('image.jpg')


if __name__ == '__main__':
    main()
Another solution may be the „Python Imaging Library” (PIL) or its successor project „Pillow“.