Python Forum
Can you print a string variable to printer - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Can you print a string variable to printer (/thread-37042.html)



Can you print a string variable to printer - hammer - Apr-26-2022

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


RE: Can you print a string variable to printer - snippsat - Apr-26-2022

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)



RE: Can you print a string variable to printer - hammer - Apr-30-2022

Thank you.
Problem resolved