Question regarding os.system

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
mfkfx
User
Beiträge: 1
Registriert: Montag 21. Dezember 2015, 00:08

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
mutetella
User
Beiträge: 1695
Registriert: Donnerstag 5. März 2009, 17:10
Kontaktdaten:

@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)
Entspanne dich und wisse, dass es Zeit für alles gibt. (YogiTea Teebeutel Weisheit ;-) )
Sirius3
User
Beiträge: 17750
Registriert: Sonntag 21. Oktober 2012, 17:20

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'])
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“.
Antworten