Python Forum

Full Version: Can you print a string variable to printer
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I can not send a string variable to the printer because it keeps looking for a file. I have printed the string variable out on the terminal window and it is formatted and looks the way i want it but need a hard copy.

I am using the variable to temporarily store lines of text with new line '\n':
self.txt_print_var=self.txt_print_var+t+'\n'

To try and print:
os.system('lpr self.txt_print_var')

lpr: Error - unable to access "self.txt_print_var" - No such file or directory

Is there a way to print variable or am I going to have to create a file to get it to work
Don't use os.system anymore it has been replaced bye subprocess.
To print a variable can eg use Popen.stdin
Something like untested.
import subprocess

var = 'Test print'
lpr = subprocess.Popen(["lpr"], stdin=subprocess.PIPE)
lpr.stdin.write(var)
With run.
import subprocess
from io import StringIO

var = 'Test print'
var_file = StringIO(var)
lpr = subprocess.run(["lpr"], var_file)
Thank you.
Problem resolved