Command line scripts

From Scribus Wiki
Revision as of 06:37, 15 September 2015 by Berteh (talk | contribs) (→‎Options: -pa <list< -> -pa <single arg> (+repeat))
Jump to navigation Jump to search

With Scribus 1.5.1, the command line launch of scribus enables to start a script in scribus.

Calling syntax


Various options enable to specify the behaviour

  • --python-script <> or -py <> : specifies the name of the script to be launched
  • --python-arg <flag or argument> [optional value] or -pa <flag or argument> [optional value] : arguments for the script (repeat as needed).
  • -g : No GUI. Scribus wont display any dialogs or windows and will exit once the script is ended. This prevent dialogs to interrupt the script.
  • -ns : no splashscreen.

--python-arg option syntax

This option enable the script to receive additional parameters that tweak its behaviour.

This option and its parameters list have to be the last option on the command line, just before the name of the SLA document that scribus opens, when there is one. Other scribus options have to be specified first, at the begining of the command line.

Possible parameters :

  • --python-arg can receive 'flags' (options without parameter) and 'options' (with parameters)
  • --python-arg car receive options with '-' or without. The script receive the flags and options and their value "as is", with or without '-' as is on the command line. It's up to the coder to choose the name of the options (with or without -) and up to script to parse the received options accordingly. Scribus core developper recommend passing options without -.
  • each '--python-arg' or '-pa' can only receive either one flag or one parameter and its values.

Examples of possible calls, with flags and options, with or without sla document opened, with various possible option syntax :

# only one short flag  + scribus doesnt open a document (the script itself does it)
scribus -py --python-arg v

# only a flag with long name + scribus opens a document the script will edit.
scribus -py --python-arg verbose mydoc.sla

# option with value
scribus -py --python-arg verbose yes

# more options + works on the scribus-opened mydoc.sla
scribus -py --python-arg v -pa w 500 -pa h 200 mydoc.sla

# -- separator required here
scribus -py --python-arg v -pa w 500 -pa h 200 -pa verbose -- mydoc.sla

Opened scribus document

Some script open the document they edit. Some other scripts require a document to be opened in scribus previously. Also when using --python-script argument, scribus can open a document before launching the script.

  • when no scribus document is specified, it's up to the script to create or open the document(s) it wants to work with.

example : a script that creates a blank square document would be called so :

scribus -g -ns   -py   -pa side 1000
  • when specified, the scribus document filename has to be last on the command line

example : a script that adds a coloured background would require the document to be specified on the command line

scribus  -py   -pa backgroundcolor red   article.sla


scribus  -py   -pa verbose   -pa backgroundcolor red   article.sla
  • -- separator marks the end of the options and the beginning of the positional arguments.

When a -- separator is placed in the command line, the following argument is a document's filename that scribus has to open before launching the script. -- separator is required when the last script option is a single flag because it enables scribus to know that the last argument is not the value for the last script option, because it is a document that has to opened before launching the script :

scribus   -py   -pa backgroundcolor red   -pa verbose  --  article.sla

Accessing scripts parameters in the script

'import sys' enables to access the command line arguments in sys.argv array. The script defines a 'main' function that receives argv and behaves accordingly.

if __name__ == '__main__':

The argv array contains each option as it is on the command line. There is no preprocessing of the dash - or doubledash -- preceding a parameter. When you pass '-w' or '--width' you will get '-w' or '--width' (not 'w' or 'width').

See examples below.

Example of command line script without arguments

Usefull 'Create PDF out of existing scribus document' script

# Produces a PDF for the SLA passed as a parameter.
# Uses the same file name and replaces the .sla extension with .pdf
# usage:
# scribus -g -py file.sla

import os

if scribus.haveDoc() :
    filename = os.path.splitext(scribus.getDocName())[0]
    pdf = scribus.PDFfile()
    pdf.file = filename+".pdf"
else :
    print("No file open")

The script can also edit the file before saving it

Here, the script writes into each of the 2 first textframes. It relies on the fact that the default name for the 2 first textframes is Text1 and Text2. Adapt to your documents and to your UI language ! For example in french the textframes would be Texte1 and Texte2)

import scribus
scribus.setText('Name', 'Text1') # get 'Name' and 'Address' from database
scribus.setText('Address', 'Text2')
pdf = scribus.PDFfile()
pdf.file = 'output1.pdf'

Then run scribus as follow:

scribus --python-script

and you have your output1.pdf file created!

In a script below, we will see how the content to be written can be specified using some command line for the script.

Examples of command line script with argument

Debuging script

Hello world script with arguments

This '' script says hello only when it receives "hello" as an argument. It then says goodbye.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# example calls :  
# scribus151svn -g -py --python-arg 1 2  # wont say hello
# scribus151svn -g -py --python-arg hello you # will say hello

import sys

import sys, scribus

def main(argv):
    i = 1;
    # parse each arguments 
    while i < len(argv):
        if argv[i] == "hello":
            print "hello world"
        i = i + 1
    if sayhello=="idontknow":
        print "Sorry i wasnt asked to say Hello";
    print "good bye"

if __name__ == '__main__':

Edit document and create PDF, using the command line to state the text to be inserted

This script reads the command lines options, looks for the value of the 'text' option and insert the found text in the document. It then creates the PDF.

It uses getopt to parse the options. There are 3 possible options :

  • The 'text' option can either be '-t' or '--text' and requires a value.
  • -h for help. Its a flag : no value expected.
  • -o or --output to specify the name of the PDF output file. It requires a value.
# Open the SLA file passed to Scribus, replace the content of the text frame named "placeholder" with
# the value in the -t argument and produce a PDF file named as defined by the -o argument.
# usage:
# - create a SLA file with a text frame named "placeholder"
# - run scribus -g -py -pa -o file.pdf -pa -t "welcome to scribus" file.sla
# (c) MIT Ale Rimoldi

import sys
import getopt
import scribus

# print(sys.argv)

text_usage = "scribus -g -py " + sys.argv[0] + " -pa -o <outputfile.pdf> -pa -t <text place holder> <inputfile.sla>"
pdf_file = ''
text_placeholder = ''

  opts, args = getopt.getopt(sys.argv[2:],"ho:t:",["output=", "text="])
except getopt.GetoptError:

for opt, arg in opts:
  if opt == "-h":
  elif opt in ("-o", "--output"):
     pdf_file = arg
  elif opt in ("-t", "--text"):
     text_placeholder = arg

if (pdf_file == "" or text_placeholder == "") :

if scribus.haveDoc() :
    scribus.setText(text_placeholder, "placeholder")
    pdf = scribus.PDFfile()
    pdf.file = pdf_file
else :
    print("No file open")

Script to print the required height for a text to be imported into a textframe

That '' script receives a text filename as a command line argument, opens it, puts its content in the first text frame of the Scribus document and adapts height of the text frame to fit the text. It then prints the required height and exits. It has to be launched with an opened scribus document.

  • create script (with following code)
  • have a sample.txt ready with some text inside
  • create somedocument.sla scribus file having at least a 'Text1' textframe on one of its page (this is the default name for the first created textframe in english UI scribus : It will be Texte1 for french UI. So adapt to your UI langage or rename the textframe using the Property Palette )

Launch script with arguments :

scribus -g -py --python-arg -storyfile sample.txt somedocument.sla

'' script :

#!/usr/bin/env python
# -*- coding: utf-8 -*-

""" : Imports into text1 textframe the content of -storyfile option textfile and adapts height of the text frame to fit the text.
Return the computed depth of the text frame

Run with the command line
	scribus -g -py --python-arg -storyfile sample.txt depthtemplate.sla

- sample.txt is the text file to measure.
- depthtemplate.sla is a document with a single, empty text frame.

Tested with scribus 1.5.0

Author: William Bader

11Aug14 wb initial version
15Dec14 wb get the file name from STORYFILE
19Aug15 wb get the file name from the command line
13Sep15 change comment to fit merged version syntax for arguments


# check that the script is running from inside scribus

	from scribus import *
except ImportError:
	print 'This script only runs from within Scribus.'

# get the os module

	import os

except ImportError:
	print 'Could not import the os module.'

# get the sys module

	import sys

except ImportError:
	print 'Could not import the sys module.'

def main(argv):

	# The first text frame of the current document defines the style

		storyfile = ""

		i = 1;
		while i < len(argv):
			if argv[i] == "-storyfile":
				storyfile = argv[i+1]
			i = i + 1

		if storyfile == "":
			print 'Warning: -storyfile not given, checking environment'
			storyfile = os.environ['STORYFILE']

		print 'Error: Pass the story file with the --python-arg-storyfile argument or the STORYFILE environment variable'

		storytext = open(storyfile, 'r').read()
		print 'Error: Story file "', storyfile, '" not found.'

		print 'Error: The document does not have an object called Text1.'

		print 'Error: The document does not have a text frame.'

		ov = textOverflows()
		width, depth = getSize()
		if ov:
			baddepth = depth
			gooddepth = 100
			baddepth = 0
			gooddepth = depth
		while baddepth < gooddepth:
			trydepth = (baddepth + gooddepth) / 2
			sizeObject(width, trydepth)
			tryov = textOverflows()
			if tryov:
				baddepth = trydepth + 0.0001
				baddepth = baddepth + 0.0001
				gooddepth = trydepth
		sizeObject(width, gooddepth)

		print 'The depth is ', str(gooddepth)
		print 'Error: not a text frame.'

# start the script

if __name__ == '__main__':
	if haveDoc():
		print 'Error: You need to have a document open before you can run this script succesfully.'