how to print string directly on cups printer (python, debian) - python

Hi is there any way to directly print a string on a cups printer from code?
what i have found is a way to print from file like so:
import cups
conn = cups.Connection ()
printers = conn.getPrinters ()
emptyDict = {}
AvailablePrinters = list(printers.keys())
PrinterUsing = AvailablePrinters[0]
conn.printFile(PrinterUsing, "./FileName", "title", emptyDict)
problem is that i cannot save files in this case :/
if you have any idea for a total python noob - any help appreciated!
Thanks!!

Related

2 way to call a resource in Flask-Restful?

I'm learning and using Python, Flask and Flask-Restful for traineeship and I got a question :
Right now I've something like this
class CheckTXT(Resource):
def get(self):
import dns.resolver
dmn = request.args.get('dmn')
answers = dns.resolver.query(dmn, 'TXT')
c = []
for rdata in answers:
for txt_string in rdata.strings:
c.append(txt_info(dmn, txt_string))
end = time.time()
tm = end - start
return lookup("TXT", dmn, c, tm)
and
api.add_resource(CheckTXT, '/lookup/txt')
I'd like to call it by 2 way :
lookup/txt?dmn=stackoverflow.com
/lookup/txt/stackoverflow.com
The first one is working but I don't know how to do the second or even if it's possible.
Someone can help me ?
Thanks for your attention and your patience ! You're helping a young padawan ahah
Yes you can use below as endpoint and possible with flask resful
/lookup/txt/stackoverflow.com
for that you need to add resources like
api.add_resource(CheckTXT, '/lookup/txt/<string:name>') and you can access that field in your implementation like below
class CheckTXT(Resource):
def get(self,name):
print name

How to remove completed torrent using libtorrent rasterbar python binding?

I have a python script that downloads files using libtorrent python binding. I just want to know how to remove the torrent once the download is complete.
I'm posting here the example script I used to make mine (I'm not posting mine because it's too large, it has database parts).
import libtorrent as lt
import time
ses = lt.session()
params = { 'save_path': '/home/downloads/'}
link = "magnet:?xt=urn:btih:4MR6HU7SIHXAXQQFXFJTNLTYSREDR5EI&tr=http://tracker.vodo.net:6970/announce"
handle = lt.add_magnet_uri(ses, link, params)
print 'downloading metadata...'
while (not handle.has_metadata()): time.sleep(1)
print 'got metadata, starting torrent download...'
while (handle.status().state != lt.torrent_status.seeding):
print '%d %% done' % (handle.status().progress*100)
time.sleep(1)
Thanks.
you call remove_torrent() on the session object, passing in the torrent_handle to remove.
http://libtorrent.org/reference-Core.html#remove_torrent()
In your script:
ses.remove_torrent(handle)

ssh result seems to only be 16bits in python with paramiko

im using paramiko in python 2.7 to connect to a cisco router, send a command and then parse the output of the command in a for loop.
the problem seems to be that the returning result is limited to 65535 characters (16bits). I printed the output and pasted it in an editor to count the characters and thats wht it gave me. Im sure im doing this very wrong because im learning python as I go hehe. here is the code:
import sqlite3
import paramiko
import time
import re
def disable_paging(remote_conn):
'''Disable paging on a Cisco router'''
remote_conn.send("terminal length 0\n")
time.sleep(1)
output = remote_conn.recv(10000)
return output
if __name__ == '__main__':
username = 'user'
password = 'password'
db = sqlite3.connect('cmts-priv.sqlite')
cursor = db.cursor()
cursor.execute('''SELECT ID, ip, hostname, uptime, active, cmtstype FROM cmts''')
all_rows = cursor.fetchall()
print "Producing report. This takes a few seconds so be patient and do not refresh\n"
for row in all_rows:
if (row[4] == 1):
print "Docsis 1.x modems for : " + row[2]
print"\n"
remote_conn_pre = paramiko.SSHClient()
remote_conn_pre.set_missing_host_key_policy(
paramiko.AutoAddPolicy())
ip=row[1]
remote_conn_pre.connect(ip, username=username, password=password)
remote_conn = remote_conn_pre.invoke_shell()
disable_paging(remote_conn)
remote_conn.send("\n")
remote_conn.send("show cable modem docsis version | inc 1\.[10] 1\.[10]\n")
time.sleep(5)
output = remote_conn.recv(100000000)
output = output.split("\n")
remote_conn_pre.close()
#print output
for i in output:
if "0013.11" not in i and "0015.96" not in i and "0015.a2" not in i and "0015.a3" not in i and "0015.a4" not in i and "0015.ce" not in i and "0015.cf" not in i and "0015.d0" not in i:
X = '([0-9a-fA-F]{4}\.[0-9a-fA-F]{4}\.[0-9a-fA-F]{4})'
c = re.compile(X).finditer(i)
if c:
for y in c:
print i[y.start(): y.end()]
print "\n=============================\n"
The result this would give to the output variable would be as follow:
00a0.7373.2a14 C4/0/U1 online 11 1.0 1.0 tdma NB
00a0.7372.ed18 C4/0/U1 online 12 1.0 1.0 tdma NB
00a0.7373.2af2 C4/0/U0 online 20 1.1 1.1 tdma NB
.....
with about 3500 results per router
Then i extract the macs after i filter the ones i dont want and output them in a list. the problem is the result im getting back from the router seems to stop at 16bits when i actually would get much more. it stops at about 1/6th compared to if i produce the output directly in the router cli. I tried to play with timeouts and the sleep and the recv buffer. i just cant figure this one out :(
of and the sqlite db stores a few things bbecuase i use it for a few scripts. what im getting with row[1] is the ip of the router to feed it to the connect string.
Im sure a bunch of you will say im complicating my life as hell but like i said i am learning all of this from google searches hehe and then trying to understand it. this will evolve for sure but for now im really stuck in a pickle with this partial and incomplete result im getting from my routers. help :(
You need to put a loop around your recv, something like:
buff = ''
while not buff.endswith(':~# '):
resp = chan.recv(9999)
buff += resp
print(resp)
See this example: https://gist.github.com/rtomaszewski/3397251

I need a super-duper simple CGI Python photo upload

I've looked through tons of answers but the truth is, I only know super basic python and I really need help. I don't know the os module or anything like that and I can't use PHP (not that I know it anyway, but it's not permitted) and I need something so easy that I can understand it.
Basically, I need a CGI upload (I don't need the HTML form, I've got that much down) that will take the photo and save it. That's it. I don't need any fancy place for it to save, I just need the file to be properly uploaded from the form.
I've got various versions of this function and I can't get them working because I don't understand them so PLEASE HELP!!!
import cgi
def savefile (filename, photodoc):
form=cgi.FieldStorage()
name=form[filename]
period=name.split(.)
if period[1]=="jpeg" or period[1]=="jpg" or period[1]=="png":
idk what to do
else:
make an error message
This cgi program will "take the photo and save it. That's it."
#!/usr/bin/python2.7
import cgi
field=cgi.FieldStorage()['fieldname']
open(field.filename, 'wb').write(field.value)
Among the things it doesn't do are error checking and security checking, and specifying in what directory the files should be saved.
Duplicate question but here's what you need:
Depending if windows or linux, first set to binary mode:
try:
import msvcrt
msvcrt.setmode (0, os.O_BINARY)
msvcrt.setmode (1, os.O_BINARY)
except ImportError:
pass
Then:
form = cgi.FieldStorage()
name = form[filename]
period = name.split('.') #You need the quotes around the period
if period[1]=='jpeg' or period[1] == 'jpg' or period[1] =='png':
if upload.filename:
name = os.path.basename(upload.filename)
out = open(YOUR_FILEPATH_HERE + name, 'wb', 1000)
message = "The file '" + name + "' was uploaded successfully"
while True:
packet = upload.file.read(1000)
if not packet:
break
out.write(packet)
out.close()
else:
print 'Error'
Some sources:
How to use Python/CGI for file uploading
http://code.activestate.com/recipes/273844-minimal-http-upload-cgi/

Python Precommit hook, Looking at lines for some text

Hello, my question is regarding a Python script I am trying to get to work. The point of this is that when someone makes a SVN Commit they see a login template with four lines: Branch, Bug_Number, Feature affected and Overview. Now I am trying to write a script to make sure that they wrote something on it to make sure no one enters a empty log to commit.
Here is what I have so far in python its based on a old python script.
print "Importing the items"
import re
import sys
import os
print "Initializing the list."
argsList = []
hndFile = open(sys.argv[1],"r")
for line in hndFile:
argsList.append(line)
hndFile.close()
print "Checking what is blank"
faOK = ovOK = False
for line in argsList:
line = line.strip()
if line.startswith('FEATURE_AFFECTED:'):
faOK = line[17:] != ''
if line.startswith('OVERVIEW:'):
ovOK = line[9:] != ''
if not faOK:
print "You Must Enter the Feature Affected"
ret = -1
elif not ovOK:
print "You Must Enter an Overview of the Fix"
ret = -1
else:
ret = 0
print "Finishing the script"
sys.exit(ret)
Any advice would help. I am using Windows XP and currently nothing is happening. I am also using collabnet svn. Currently nothing is happening when I try to run this script. I know I haven't added svnlook in the script I cant really think of where to add and for the variable for it. Thank you.

Categories