Re: from calendar import* doesn't import everything
see http://docs.python.org/tutorial/modules.html#importing-from-a-package http://stackoverflow.com/questions/2187583/whats-the-python-all-module-level-variable-for I know the 1st link is for importing from a package but the same applies for modules -- http://mail.python.org/mailman/listinfo/python-list
send function keys to a legacy DOS program
Greetings, We have an old barcode program (MSDOS and source code unavailable.) I've figured out how to populate the fields (by hacking into one of the program's resource files.) However, we still need to hit the following function keys in sequence. F5, F2, F7 Is there a way to pipe said keys into the program? I know it's not really a python problem but I got nowhere else to go. I've tried other barcode solutions but none give the same output. -- http://mail.python.org/mailman/listinfo/python-list
Re: send function keys to a legacy DOS program
On Mar 20, 7:30 am, Alexander Gattin wrote: > On Sun, Mar 20, 2011 at 12:52:28AM +0200, > > You need to place 2 bytes into the circular buffer > to simulate key press. Lower byte is ASCII code, > higher byte is scan code (they are the same for > functional keys, whe using default keycode set#1): > > F5: 0x3F 0x3F > F2: 0x3C 0x3C > F7: 0x41 0x41 > > -- > With best regards, > xrgtn looks promising. will give this a try. thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: send function keys to a legacy DOS program
On Tue, Mar 29, 2011 at 9:59 PM, Alexander Gattin wrote: > I'm not sure regarding the ASCII part. I think it > might need to be set to 0x00 for all functional > keys instead of 0x3F/0x3C/0x41, but probably no > application actually cares. > > Another thing is that you may need to send key > release after key press in order for the > application to trigger the F5/F2/F7 event. I'm not > sure what the scan codes for F5/F2/F7 releases > are, but think that they may be: > > F5: 0xBF > F2: 0xBC > F7: 0xC1 > > -- > With best regards, > xrgtn > appreciate all the help. unfortunately, my hard drive crashed and badly. thus was unable to investigate this further. as I was running out of time, we're now going for a reimplementation of the legacy barcode program. was fortunate to find an implementation that gives the same output (we're testing thoroughly and we may have found a winner) oh btw, it was a seagate 250GB drive for my dell laptop may need to pay somebody to try to recover my personal files. all work files are in version control so they're ok -- http://mail.python.org/mailman/listinfo/python-list
retrieve source code from code object as returned by compile()
Is there a way to get the original source? I am trying to retrieve the main script from a py2exe'd old program. The programmer neglected to commit to SVN before leaving. Using "Easy Python Decompiler" I am able to get the source for the imported modules. Using "Resources Viewer" from PlexData and some code I am able to retrieve the code object. I am however stumped as to how to retrieve the source from this code object. PythonWin 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for further copyright information. >>> s = 'import time\nprint time.time()\n' >>> c = compile(s, 'foo.py', 'exec') >>> exec(c) 1398299623.77 >>> c at 01E5C5C0, file "foo.py", line 1> >>> for n in dir(c): ... if n.startswith('_'): continue ... print n ... a = getattr(c, n) ... print type(a) ... print `a` ... print ... co_argcount 0 co_cellvars () co_code 'd\x00\x00d\x01\x00k\x00\x00Z\x00\x00e\x00\x00i\x00\x00\x83\x00\x00GHd\x01\x00S' co_consts (-1, None) co_filename 'foo.py' co_firstlineno 1 co_flags 64 co_freevars () co_lnotab '\x0c\x01' co_name '' co_names ('time',) co_nlocals 0 co_stacksize 2 co_varnames () >>> len(s) 30 >>> len(c.co_code) 27 >>> -- https://mail.python.org/mailman/listinfo/python-list
Re: retrieve source code from code object as returned by compile()
On Thursday, April 24, 2014 1:53:38 PM UTC+8, Gregory Ewing wrote: > Alternatively you could create a .pyc file out of the code > object and then use Easy Python Decompiler on that. The > following snippet of code should do that: > > (Taken from: > > http://stackoverflow.com/questions/8627835/generate-pyc-from-python-ast) Woohoo! Success! Thank you Greg! -- https://mail.python.org/mailman/listinfo/python-list
Re: About zipfile on WinXP
here's a small script I wrote and use note the line arcname = os.path.splitdrive(p)[-1].lstrip(os.sep) if I comment out `.lstrip(os.sep)`, I get a zip file like rzed describes ### import sys import zipfile import time import os if __name__ == '__main__': pths = sys.argv[1:] assert pths, 'usage: %s file1 [file2 [file3 ...]]' % sys.argv[0] zpth = os.path.abspath(time.strftime('%Y%m%d%H%M%S.zip')) zf = zipfile.ZipFile(zpth, 'w', zipfile.ZIP_DEFLATED) for p in pths: p = os.path.abspath(p) arcname = os.path.splitdrive(p)[-1].lstrip(os.sep) zf.write(p, arcname) print arcname, p zf.close() print '%s files written to %s' % (len(pths), zpth) ### -- http://mail.python.org/mailman/listinfo/python-list
Re: tools to manipulate PDF document?
have you seen http://www.pdfhacks.com/pdftk/ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to fill a form
Sulsa wrote: > On Tue, 15 Aug 2006 03:37:02 - > Grant Edwards <[EMAIL PROTECTED]> wrote: > > > On 2006-08-15, Sulsa <[EMAIL PROTECTED]> wrote: > > > > > I want to fill only one smiple form so i would like not to use > > > any non standard libraries. > > > > Then just send the HTTP "POST" request containing the fields > > and data you want to submit. > > but i don't know how to post these data if i knew there there would > be no topic. http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/146306 -- http://mail.python.org/mailman/listinfo/python-list
Re: Get EXE (made with py2exe) path directory name
try, if hasattr(sys, 'frozen'): me = sys.executable else: me = sys.argv[0] -- http://mail.python.org/mailman/listinfo/python-list
Re: Again, Downloading and Displaying an Image from the Internet in Tkinter
cannot help you with Tkinter but... save=open("image.jpg","wb") save.write(web_download.read()) save.close() perhaps this would let you open the file in Paint -- http://mail.python.org/mailman/listinfo/python-list
Re: Database read and write
Stan Cook wrote: > will ope, read, and write to a Dbase 3 or 4 file? I know I have one in VB6 that I've been meaning to translate to Python but... (do not have time/am lazy/does not work with indexes) did a google search for you though http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362715 http://www.garshol.priv.no/download/software/python/dbfreader.py -- http://mail.python.org/mailman/listinfo/python-list
Re: Python SHA-1 as a method for unique file identification ? [help!]
EP wrote: > This inquiry may either turn out to be about the suitability of the > SHA-1 (160 bit digest) for file identification, the sha function in > Python ... or about some error in my script. > > This is on Windows XP. > > def hashit(pth): > fs=open(pth,'r').read() > sh=sha.new(fs).hexdigest() > return sh > cannot comment on the suitability of SHA for your use-case but shouldn't you be opening the file in binary mode? fs=open(pth,'rb').read() -- http://mail.python.org/mailman/listinfo/python-list
Re: web app breakage with utf-8
replacing connection.character_set_name instance method seems to work but is this the correct/preferred way? >>> import MySQLdb >>> MySQLdb.get_client_info() '4.1.8' >>> import sys >>> sys.version '2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)]' >>> sys.platform 'win32' >>> cred = {'passwd': 'secret', 'host': 'myhost', 'db': 'mydb', 'user': >>> 'justin'} >>> insert = 'insert into unicodetest2 (foo) values (%s)' >>> alpha = u'\N{GREEK SMALL LETTER ALPHA}' >>> alpha u'\u03b1' >>> conn.close() >>> conn = MySQLdb.connect(**cred) >>> cur = conn.cursor() >>> cur.execute(insert, 'a') 1L >>> conn.commit() >>> conn.close() >>> conn = MySQLdb.connect(**cred) >>> cur = conn.cursor() >>> cur.execute(select) 1L >>> cur.fetchall() ((9L, 'a'),) >>> conn.close() >>> conn = MySQLdb.connect(**cred) >>> cur = conn.cursor() >>> cur.execute(insert, alpha) Traceback (most recent call last): File "", line 1, in ? File "E:\Python23\Lib\site-packages\MySQLdb\cursors.py", line 95, in execute return self._execute(query, args) File "E:\Python23\Lib\site-packages\MySQLdb\cursors.py", line 114, in _execute self.errorhandler(self, exc, value) File "E:\Python23\Lib\site-packages\MySQLdb\connections.py", line 33, in defaulterrorhandler raise errorclass, errorvalue LookupError: unknown encoding: latin1_swedish_ci >>> conn.close() >>> conn = MySQLdb.connect(**cred) >>> def character_set_name(*args, **kwargs): return 'utf-8' ... >>> character_set_name() 'utf-8' >>> conn.close() >>> conn = MySQLdb.connect(**cred) >>> conn.character_set_name() 'latin1_swedish_ci' >>> import new >>> conn.character_set_name = new.instancemethod(character_set_name, conn, >>> conn.__class__) >>> conn.character_set_name() 'utf-8' >>> cur = conn.cursor() >>> cur.execute(insert, alpha) 1L >>> conn.close() >>> conn = MySQLdb.connect(**cred) >>> conn.character_set_name() 'latin1_swedish_ci' >>> cur = conn.cursor() >>> cur.execute(select) 2L >>> cur.fetchall() ((10L, '\xce\xb1'), (9L, 'a')) >>> conn.close() >>> conn = MySQLdb.connect(unicode='utf-8', **cred) >>> conn.character_set_name() 'latin1_swedish_ci' >>> cur = conn.cursor() >>> cur.execute(select) 2L >>> cur.fetchall() ((10L, u'\u03b1'), (9L, u'a')) >>> conn.close() >>> conn = MySQLdb.connect(**cred) >>> cur = conn.cursor() >>> cur.execute(select) 2L >>> cur.fetchall() ((10L, '\xce\xb1'), (9L, 'a')) >>> conn.close() >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: Using "Content-Disposition" in HTTP download
[EMAIL PROTECTED] wrote: > What is the correct way to download a file through HTTP and save it to > the file name suggested by "Content-Disposition"? > Perhaps something along the lines of the following? >>> url = >>> r'http://www.4so9.com/cauca/files/ban-doc/francois/stingray/198%20lb%20stingray%201%20.JPG' >>> proxy = 'proxy02:8080' >>> import httplib >>> c = httplib.HTTPConnection(proxy) >>> c.request('GET', url) >>> resp = c.getresponse() >>> for k in resp.msg.keys(): ... print resp.msg.getallmatchingheaders(k) ... ['Content-Length: 64632\r\n'] ['Proxy-Connection: close\r\n'] ['X-Cache: HIT from SPSweb\r\n'] ['Accept-Ranges: bytes\r\n'] ['Server: Apache/2.0.51 (Fedora)\r\n'] ['Last-Modified: Fri, 03 Dec 2004 16:57:30 GMT\r\n'] ['ETag: "3b2375-fc78-8c13280"\r\n'] ['Date: Tue, 05 Sep 2006 10:35:48 GMT\r\n'] ['Content-Type: image/jpeg\r\n'] ['Age: 31440\r\n'] >>> data = resp.fp.read() >>> len(data) 64632 >>> data[:100] '\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x02\x02\x00\x00\x00\x00\x00\x00\xff\xe1\x057Exif\x00\x00II*\x00\x08\x00\x00\x00\t\x00\x0f\x01\x02\x00\x06\x00\x00\x00z\x00\x00\x00\x10\x01\x02\x00\x13\x00\x00\x00\x80\x00\x00\x00\x12\x01\x03\x00\x01\x00\x00\x00\x01\x00\x00\x00\x1a\x01\x05\x00\x01\x00\x00\x00\x93\x00\x00\x00\x1b\x01\x05\x00\x01\x00\x00\x00\x9b\x00\x00\x00' >>> resp.fp.close() >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: 22, invalid agument error
> sockobj.bind(('',40007)) tried on my N6600 with same error try using your phone's IP instead of the empty string '' tried sockobj.bind(('127.0.0.1',40007)) and did not get an error -- http://mail.python.org/mailman/listinfo/python-list
Re: 22, invalid agument error
Infinite Corridor wrote: > Justin Ezequiel wrote: > > > > tried sockobj.bind(('127.0.0.1',40007)) and did not get an error > > I didn't get an error either, but the whole thing hangs up, and I am > forced to abort the program. This has happend quite a few times > already. > Did it work for you normally? > am unable to test as my current PCs do not have bluetooth (yet) sorry -- http://mail.python.org/mailman/listinfo/python-list
Re: FtpUtils Progress Bar
[EMAIL PROTECTED] wrote: > > Does anyone have an example on how to show the progress of the > upload/download when using ftputil? > haven't used ftputil in quite a while ... but using ftplib... import ftplib class Callback(object): def __init__(self, totalsize, fp): self.totalsize = totalsize self.fp = fp self.received = 0 def __call__(self, data): self.fp.write(data) self.received += len(data) print '\r%.3f%%' % (100.0*self.received/self.totalsize), if __name__ == '__main__': host = 'ftp.microsoft.com' src = '/deskapps/games/public/Hellbender/heltrial.exe' c = ftplib.FTP(host) c.login() size = c.size(src) dest = 'heltrial.exe' f = open(dest, 'wb') w = Callback(size, f) c.set_pasv(0) c.retrbinary('RETR %s' % src, w, 32768) f.close() c.quit() -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple FTP download using Muliti thread
import ftplib, posixpath, threading from TaskQueue import TaskQueue def worker(tq): while True: host, e = tq.get() c = ftplib.FTP(host) c.connect() try: c.login() p = posixpath.basename(e) fp = open(p, 'wb') try: c.retrbinary('RETR %s' % e, fp.write) finally: fp.close() finally: c.close() tq.task_done() if __name__ == '__main__': q = TaskQueue() host = 'ftp.microsoft.com' c = ftplib.FTP(host) c.connect() try: c.login() folder = '/deskapps/kids/' for n in c.nlst(folder): if n.lower().endswith('.exe'): q.put((host, n)) finally: c.close() numworkers = 4 for i in range(numworkers): t = threading.Thread(target=worker, args=(q,)) t.setDaemon(True) t.start() q.join() print 'Done.' -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple FTP download using Muliti thread
Fredrik Lundh wrote: > Justin Ezequiel wrote: > > > from TaskQueue import TaskQueue > > what Python version is this ? > > oops. forgot to note... http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/475160 -- http://mail.python.org/mailman/listinfo/python-list
Re: Multiple FTP download using Muliti thread
johnny wrote: > When I run the following script, with host and password and username > changed, I get the following errors: > raise error_temp, resp > error_temp: 421 Unable to set up secure anonymous FTP > > Dose the host should allow 4 simultaneous login at a time? > does it work using ftp.microsoft.com? post your code -- http://mail.python.org/mailman/listinfo/python-list
Re: Script Error
ie.Navigate ('URL') ie.SetTextBox(username,'txtUserId',0) not sure but shouldn't you be waiting for navigate to actually finish loading the page before setting fields? see the ie.Busy or ie.readyState properties/methods -- http://mail.python.org/mailman/listinfo/python-list
Re: Comparing files in a zip to files on drive
kj7ny wrote: > compare a file on a hard drive to a file in a python created zip file > to tell if the file has changed? >>> fileondisk = r'C:\Documents and Settings\power\Desktop\ES3dc+Template.3f' >>> zipondisk = r'C:\Documents and Settings\power\Desktop\temps.zip' >>> import zipfile >>> z = zipfile.ZipFile(zipondisk) >>> z.namelist() ['ES1+Template.3f', 'ES3sc+Template.3f', 'ES3dc+Template.3f'] >>> info = z.getinfo('ES3dc+Template.3f') >>> info.CRC 1620938006 >>> import binascii >>> checksum = 0 >>> fp = open(fileondisk, 'rb') >>> while 1: ... data = fp.read(32*1024) ... if not data: break ... checksum = binascii.crc32(data, checksum) ... >>> checksum 1620938006 >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expressions, unicode and XML
import codecs f = codecs.open(pth, 'r', 'utf-8') data = f.read() f.close() ## data = re.sub ... f = codecs.open(pth, 'w', 'utf-8') f.write(data) f.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expressions, unicode and XML
>> when I replace it end up with nothing: i.e., just a "" character in my >> file. how are you viewing the contents of your file? are you printing it out to stdout? are you opening your file in a non-unicode aware editor? try print repr(data) after re.sub so that you see what you actually have in data btw, from where did you get you XML files? -- http://mail.python.org/mailman/listinfo/python-list
Tiny RML2PDF re rml_1_0.dtd download
Can somebody please give me a URL to where I can download the DTD? I've Googled and browsed all through http://openreport.org/ with no success. I've subscribed to the OpenReport mailing list but messages I send to [EMAIL PROTECTED] bounce back with an unknown user: "openreport-list" BTW, anyone here using Tiny RML2PDF? Any comments? Thank you. -- http://mail.python.org/mailman/listinfo/python-list
Re: passing arguments to tcpserver classes
On Jun 13, 10:19 pm, Eric Spaulding <[EMAIL PROTECTED]> wrote: > Is there an easy way to pass arguments to a handler class that is used > by the standard TCPServer? > > normally --> srvr =SocketServer.TCPServer(('',port_num), TCPHandlerClass) > > I'd like to be able to: srvr =SocketServer.TCPServer(('',port_num), > TCPHandlerClass, (arg1,arg2)) > > And have arg1, arg2 available via TCPHandlerClass.__init__ or some other > way. > I use the following method. Would also like to know if there's another way to do this. class SVNUpdateRequestHandler(SocketServer.BaseRequestHandler): def __init__(self, svn, wms, *args, **kwargs): self.svn = svn self.wms = wms # NEED to set additional attributes before parent init SocketServer.BaseRequestHandler.__init__(self, *args, **kwargs) def handle(self): pass def get_handler(svn, wms): class RequestHandler(SVNUpdateRequestHandler): def __init__(self, *args, **kwargs): SVNUpdateRequestHandler.__init__(self, svn, wms, *args, **kwargs) return RequestHandler def main(port, requesthandler): server = SVNUpdateServer(('', port), requesthandler) while 1: server.handle_request() if __name__ == '__main__': svn, wms = sys.argv[1:] requesthandler = get_handler(svn, wms) main(port, requesthandler) -- http://mail.python.org/mailman/listinfo/python-list
Re: something similar to shutil.copytree that can overwrite?
On Jun 20, 5:30 pm, Ben Sizer <[EMAIL PROTECTED]> wrote: > I need to copy directories from one place to another, but it needs to > overwrite individual files and directories rather than just exiting if > a destination file already exists. What version of Python do you have? Nothing in the source would make it exit if a target file exists. (Unless perhaps you have sym-links or the like.) Python 2.4.4 (#71, Oct 18 2006, 08:34:43) [MSC v.1310 32 bit (Intel)] copytree calls copy2 which calls copyfile from shutil.py: # def _samefile(src, dst): # Macintosh, Unix. if hasattr(os.path,'samefile'): try: return os.path.samefile(src, dst) except OSError: return False # All other platforms: check for same pathname. return (os.path.normcase(os.path.abspath(src)) == os.path.normcase(os.path.abspath(dst))) def copyfile(src, dst): """Copy data from src to dst""" if _samefile(src, dst): raise Error, "`%s` and `%s` are the same file" % (src, dst) fsrc = None fdst = None try: fsrc = open(src, 'rb') fdst = open(dst, 'wb') copyfileobj(fsrc, fdst) finally: if fdst: fdst.close() if fsrc: fsrc.close() # -- http://mail.python.org/mailman/listinfo/python-list
Re: something similar to shutil.copytree that can overwrite?
def copytree(src, dst, symlinks=False): """Recursively copy a directory tree using copy2(). The destination directory must not already exist. XXX Consider this example code rather than the ultimate tool. """ names = os.listdir(src) if not os.path.exists(dst): os.makedirs(dst) # add check here -- http://mail.python.org/mailman/listinfo/python-list
Re: something similar to shutil.copytree that can overwrite?
On Jun 22, 9:07 pm, Ben Sizer <[EMAIL PROTECTED]> wrote: > That's the easy bit to fix; what about overwriting existing files > instead of copying them? Do I have to explicitly check for them and > delete them? It seems like there are several different copy functions > in the module and it's not clear what each of them do. What's the > difference between copy, copyfile, and copy2? Why do the docs imply > that they overwrite existing files when copytree skips existing > files? > > -- > Ben Sizer copytree does not skip existing files if will overwrite said files I just missed the makedirs call at the start the failed makedirs call will cause the copytree function to exit completely thus you do not get your files updated but with the if exists check, your files should get overwritten -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expressions eliminating filenames of type foo.thumbnail.jpg
Why not ditch regular expressions altogether for this problem? [ p for p in os.listdir(dir) if os.path.isfile(os.path.join(dir,p)) and p.lower().find('.thumbnail.')==-1 ] -- http://mail.python.org/mailman/listinfo/python-list
Re: regular expressions eliminating filenames of type foo.thumbnail.jpg
On Jun 25, 1:00 pm, Justin Ezequiel <[EMAIL PROTECTED]> wrote: > [ p for p in os.listdir(dir) > if os.path.isfile(os.path.join(dir,p)) > and p.lower().find('.thumbnail.')==-1 ] if you really want a regexp solution, the following seems to work (?i)(?http://kodos.sourceforge.net/) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python & MySQL problem with input to table..!
On Jun 29, 4:26 pm, hiroc13 <[EMAIL PROTECTED]> wrote: > >>> import MySQLdb > >>> db = MySQLdb.connect (host = "localhost", user = "root", passwd = "pass", > >>> db = "base1") > >>> c = db.cursor () > >>> c.execute(""" INSERT INTO table1 (prvo, drugo) VALUES ('test', '1') """) > >>> c.execute("SELECT * FROM table1") > >>> res = c.fetchall () > >>> print res > > When I start this code I get ((15L, 'test', 1L),) on the screen but if > I first execute this: > > >>> import MySQLdb > >>> db = MySQLdb.connect (host = "localhost", user = "root", passwd = "pass", > >>> db = "base1") > >>> c = db.cursor () > >>> c.execute(""" INSERT INTO table1 (prvo, drugo) VALUES ('test', '1') """) > > this write to table1 > and now this: > > >>> Import MySQLdb > >>> db = MySQLdb.connect (host = "localhost", user = "root", passwd = "pass", > >>> db = "base1") > >>> c = db.cursor () > >>> c.execute("SELECT * FROM table1") > >>> res = c.fetchall () > >>> print res > > I get only this: "()" - the table1 is empty ... I write 10 times same > thing to table... only PRIMARY KEY is change > > WHY try a `db.commit()` after the INSERT -- http://mail.python.org/mailman/listinfo/python-list
Re: The file executing
On Jul 3, 9:40 am, Benjamin <[EMAIL PROTECTED]> wrote: > How does one get the path to the file currently executing (not the > cwd). Thank you os.path.dirname(sys.argv[0]) -- http://mail.python.org/mailman/listinfo/python-list
Re: ignoring a part of returned tuples
On Jul 4, 4:08 pm, noamtm <[EMAIL PROTECTED]> wrote: > What I wanted is: > for (dirpath, , filenames) in os.walk(...): > > But that doesn't work. for (dirpath, _, filenames) in os.walk(...): -- http://mail.python.org/mailman/listinfo/python-list
Re: how to execute a system command?
On May 23, 2:25 pm, wrb <[EMAIL PROTECTED]> wrote: > i want to open a excel file in a button click event. > i found that os.popen4("excel.xls") would work but it is too slow have you tried os.startfile -- http://mail.python.org/mailman/listinfo/python-list
Re: MySQLdb: ValueError Something Stupid
On Sep 7, 10:39 pm, mcl <[EMAIL PROTECTED]> wrote: > On 7 Sep, 14:11, Carsten Haese <[EMAIL PROTECTED]> wrote: > > > > > On Fri, 2007-09-07 at 05:52 -0700, mcl wrote: > > > > ValueError: invalid literal for int(): 0- > > > > args = ('invalid literal for int(): 0-',) > > > > > = > > > > Thanks Richard > > > > Sort of solved it. > > > > On that particular table it did not like * for all fields. > > > > Any reason why that would be the case ? > > > None that we can divine without more information. What's the schema for > > the table in question, which column(s) are you excluding to make the > > query work, and what kind of data is in the column(s) you're excluding? > > > -- > > Carsten Haesehttp://informixdb.sourceforge.net > > Thanks for replying. > > I did not exclude any columns and the Schema is: > > CREATE TABLE lstData ( > qlCat varchar(20) NOT NULL default '', > qlTitle varchar(255) NOT NULL default '', > qlSubTitle varchar(255) default NULL, > qlDetails text, > qlPic varchar(20) default NULL, > qlPostCode varchar(16) default NULL, > qlUpd timestamp NOT NULL default '-00-00 00:00:00' on update > CURRENT_TIMESTAMP, > KEY `idx-qlCat` (qlCat) > ) ENGINE=MyISAM DEFAULT CHARSET=latin1; > > Thanks again > > Richard saw this before on earlier MySQLdb and timestamp column try upgrading your MySQLdb see https://bugzilla.redhat.com/show_bug.cgi?id=155341 or http://www.ravenbrook.com/project/p4dti/master/code/replicator/mysqldb_support.py -- http://mail.python.org/mailman/listinfo/python-list
Re: getting local system information with python
On Mar 16, 2:27 pm, Astan Chee <[EMAIL PROTECTED]> wrote: > Hi, > I have a python script and I want to check what operating system it is > on and what the current local machine name is. > How do I do it with python? > Thanks! > Astan import platform platform.uname() -- http://mail.python.org/mailman/listinfo/python-list
Re: shutil.copy Problem
On Mar 27, 11:10 am, David Nicolson <[EMAIL PROTECTED]> wrote: > Hi, > > I wasn't exactly sure where to send this, I don't know if it is a bug > in Python or not. This is rare, but it has occurred a few times and > seems to be reproducible for those who experience it. > > Examine this code: > >>> try: > >>> shutil.copy("/file.xml","/Volumes/External/file.xml") > >>> except Exception, err: > >>> print sys.exc_info()[0] > >>> print err > > This is the output: > exceptions.UnicodeDecodeError > 'ascii' codec can't decode byte 0xd6 in position 26: ordinal not in > range(128)] > > What could the possible cause of this be? Shouldn't shutil simply be > reading and writing the bytes and not character decoding them? > > Cheers, > David what if you try it without the try...except? perhaps the UnicodeDecodeError is in the print... -- http://mail.python.org/mailman/listinfo/python-list
Re: wxPython, Syntax highlighting
On Mar 28, 2:56 pm, "Eric von Horst" <[EMAIL PROTECTED]> wrote: > I am looking for wx widget that has the ability to show text, edit the > text (like a TextCtrl) but also does syntax highlighting (if the text > is e.g. XML or HTML). > I have been looking in the latest wxPython version but I could not > really find anything. see .\wxPython2.6 Docs and Demos\samples\ide\ActiveGridIDE.py -- http://mail.python.org/mailman/listinfo/python-list
Re: BeautifulSoup vs. Microsoft
On Mar 29, 4:08 pm, Duncan Booth <[EMAIL PROTECTED]> wrote: > John Nagle <[EMAIL PROTECTED]> wrote: > > title="
Re: BeautifulSoup vs. Microsoft
On Mar 29, 6:11 pm, "Justin Ezequiel" <[EMAIL PROTECTED]> wrote: > > FWIW, seehttp://tinyurl.com/yjtzjz > hmm. not quite right. http://tinyurl.com/ynv4ct or http://www.crummy.com/software/BeautifulSoup/documentation.html#Customizing%20the%20Parser -- http://mail.python.org/mailman/listinfo/python-list
UDT wrappers
Found a couple of papers that mention Python wrappers for UDT have been written but Google fails me. Do any of you know of such wrappers? Have downloaded UDT SDK but source is in C++. http://udt.sourceforge.net/ -- http://mail.python.org/mailman/listinfo/python-list
Re: python newbie beautifulSoup question
On Apr 12, 4:15 am, Jon Crump <[EMAIL PROTECTED]> wrote: > Is it possible to feed findAll() a list of tags WITH attributes? >>> BeautifulSoup.__version__ '3.0.3' >>> s = '''\nboo\nhello\n>> a="bar">boo\nhi\n''' >>> soup = BeautifulSoup.BeautifulSoup(s) >>> def func(tag): ... if tag.name not in ('y', 'z'): return False ... if tag.name=='y': return tag.get('a')=='foo' ... return tag.get('a')=='foo' and tag.get('b')=='bar' ... >>> soup.findAll(func) [hello, hi] >>> def get_func(lst): ... def func(tag): ... for name, attrs in lst: ... if tag.name==name: ... for k, v in attrs.items(): ... if tag.get(k, None)==v: continue ... else: return False ... else: return True ... else: return False ... return func ... >>> func2 = get_func([('y', {'a': 'foo'}), ('z', {'b': 'bar', 'a': 'foo'})]) >>> soup.findAll(func2) [hello, hi] >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: os.popen() not executing command on windows xp
> import os > a = os.popen('"c:\Program Files\Grisoft\AVG Free\avgscan.exe" > "c:\program files\temp1\test1.txt"') > print a.read() > use raw strings e.g., instead of '"c:...\avgscan...' use r'"c:...\avgscan...' http://www.ferg.org/projects/python_gotchas.html#contents_item_2 -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert raw data to XML
On Jan 30, 10:42 am, [EMAIL PROTECTED] wrote: > For example the raw data is as follows > > SomeText Description>PassorFail > > without spaces or new lines. I need this to be written into an XML > file as > > > > > > > SomeText > > > PassorFail > > > > raw = r'SomeText PassorFail' import xml.dom.ext import xml.dom.minidom doc = xml.dom.minidom.parseString(raw) xml.dom.ext.PrettyPrint(doc) SomeText PassorFail -- http://mail.python.org/mailman/listinfo/python-list
Re: how to store and still search special characters in Python and MySql
On Feb 12, 12:26 pm, "ronrsr" <[EMAIL PROTECTED]> wrote: > I have an MySQL database called zingers. The structure is: > > I am having trouble storing text, as typed in latter two fields. > Special characters and punctuation all seem not to be stored and > retrieved correctly. > > Special apostrophes and single quotes from Microsoft Word are causing > a > special problem, even though I have ''ed all 's > > > Input and output is through a browser. > > > UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position > 95: ordinal not in range(128) > args = ('ascii', "update zingers set keywords = > 'a;Action;b;Religi... \n \n \n ' where zid = 422", 95, 96, 'ordinal > not > in range(128)') > encoding = 'ascii' > end = 96 > object = "update zingers set keywords = 'a;Action;b;Religi... > \n > \n \n ' where zid = 422" > reason = 'ordinal not in range(128)' > start = 95 > > the characters I am trying to add are startquote and endquote copied > and pasted from Microsoft Word. > http://tinyurl.com/2g9364 as nobody has replied yet...perhaps the above link may help -- http://mail.python.org/mailman/listinfo/python-list
Re: Python CGI - Presenting a zip file to user
On Jan 3, 7:50 am, jwwest <[EMAIL PROTECTED]> wrote: > Hi all, > > I'm working on a cgi script that zips up files and presents the zip > file to the user for download. It works fine except for the fact that > I have to overwrite the file using the same filename because I'm > unable to delete it after it's downloaded. The reason for this is > because after sending "Location: urlofzipfile" the script stops > processing and I can't call a file operation to delete the file. Thus > I constantly have a tmp.zip file which contains the previously > requested files. > > Can anyone think of a way around this? Is there a better way to create > the zip file and present it for download "on-the-fly" than editing the > Location header? I thought about using Content-Type, but was unable to > think of a way to stream the file out. > > Any help is appreciated, much thanks! > > - James import sys, cgi, zipfile, os from StringIO import StringIO try: # Windows only import msvcrt msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) except ImportError: pass HEADERS = '\r\n'.join( [ "Content-type: %s;", "Content-Disposition: attachment; filename=%s", "Content-Title: %s", "Content-Length: %i", "\r\n", # empty line to end headers ] ) if __name__ == '__main__': os.chdir(r'C:\Documents and Settings\Justin Ezequiel\Desktop') files = [ '4412_ADS_or_SQL_Server.pdf', 'Script1.py', 'html_files.zip', 'New2.html', ] b = StringIO() z = zipfile.ZipFile(b, 'w', zipfile.ZIP_DEFLATED) for n in files: z.write(n, n) z.close() length = b.tell() b.seek(0) sys.stdout.write( HEADERS % ('application/zip', 'test.zip', 'test.zip', length) ) sys.stdout.write(b.read()) b.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: Python CGI - Presenting a zip file to user
On Jan 3, 1:35 pm, jwwest <[EMAIL PROTECTED]> wrote: > Thanks! That worked like an absolute charm. > > Just a question though. I'm curious as to why you have to use the > msvcrt bit on Windows. If I were to port my app to *NIX, would I need > to do anything similar? > > - James not needed for *NIX as *NIX does not have a notion of binary- vs text- mode I seem to recall not needing the msvcrt stuff a while ago on Windows but recently needed it again for Python CGI on IIS -- http://mail.python.org/mailman/listinfo/python-list
Re: Image to browser
On Jan 16, 1:19 pm, [EMAIL PROTECTED] wrote: > On Jan 16, 12:16 am, [EMAIL PROTECTED] wrote: > > > Im using mod_python and apache2 using psp for output of page, i open a > > file and resize it with the following code > > > <% > > import Image, util > > > fields = util.FieldStorage(req) > > filename = fields.getlist('src')[0] > > > path = '/var/www/content/' + filename > > size = 128, 128 > > > im = Image.open(path) > > print im.resize(size, Image.ANTIALIAS) > > %> > > > so for one, I dont think print does much with psp as far as i can > > tell, i cant even do a print 'hello world', it has to be a > > req.write('hello world'), but i cant req.write the im.resize. The > > manual for im.resize states that its return can go ahead and be > > streamed via http but I get a blank page when im expecting to see > > image characters dumped to my screen. Python doesn't throw up any > > errors. Im not sure where else to look or what to do. > > > Thanks for any help, > > Daniel > > its worth noting that ive tried using > print "Content-Type: image/jpeg\n" > before the print im.resize and still no luck If you're using the Image module from PIL then im.resize(...) returns an Image instance. I have not used mod_python and psp, but try the following: >>> import Image >>> i = Image.open('server.JPG') >>> r = i.resize((32,32)) >>> from StringIO import StringIO >>> b = StringIO() >>> r.save(b, 'JPEG') >>> b.seek(0) >>> req.write("Content-Type: image/jpeg\r\n\r\n") >>> req.write(b.read()) There's a r.tostring(...) method but I don't see how to make that return a JPEG stream. -- http://mail.python.org/mailman/listinfo/python-list
Re: parsing json output
FWIW, using json.py I got from somewhere forgotten, >>> import json >>> url = >>> 'http://cmsdoc.cern.ch/cms/test/aprom/phedex/dev/gowri/datasvc/tbedi/requestDetails' >>> params = {'format':'json'} >>> import urllib >>> eparams = urllib.urlencode(params) >>> import urllib2 >>> request = urllib2.Request(url,eparams) >>> response = urllib2.urlopen(request) >>> s = response.read() >>> len(s) 115337 >>> s[:200] '{"phedex":{"request": [{"last_update":"1188037561","numofapproved":"1","id":"7425"}, {"last_update":"1188751826","numofapproved":"1","id":"8041"}, {"last_update":"1190116795","numofapproved":"1","id":"92' >>> x = json.read(s) >>> type(x) >>> x.keys() ['phedex'] >>> type(x['phedex']) >>> x['phedex'].keys() ['request_date', 'request_timestamp', 'request', 'call_time', 'instance', 'request_call', 'request_url'] ##json.py implements a JSON (http://json.org) reader and writer. ##Copyright (C) 2005 Patrick D. Logan ##Contact mailto:[EMAIL PROTECTED] ## ##This library is free software; you can redistribute it and/or ##modify it under the terms of the GNU Lesser General Public ##License as published by the Free Software Foundation; either ##version 2.1 of the License, or (at your option) any later version. ## ##This library is distributed in the hope that it will be useful, ##but WITHOUT ANY WARRANTY; without even the implied warranty of ##MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ##Lesser General Public License for more details. ## ##You should have received a copy of the GNU Lesser General Public ##License along with this library; if not, write to the Free Software ##Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -- http://mail.python.org/mailman/listinfo/python-list
Re: Module/Library That is Able To Use Cookies + Proxies?
On Jan 30, 12:06 pm, blackcapsoftw...@gmail.com wrote: > I would like to do is be able to log into a site that uses cookies to > store information about the user when logging in. This works fine and > dandy with ClientCookie. Now, I want to be able to do so with a proxy, urllib2 http://docs.python.org/library/urllib2.html#module-urllib2 class urllib2.HTTPCookieProcessor([cookiejar]) A class to handle HTTP Cookies. class urllib2.ProxyHandler([proxies])¶ Cause requests to go through a proxy. If proxies is given, it must be a dictionary mapping protocol names to URLs of proxies. The default is to read the list of proxies from the environment variables . To disable autodetected proxy pass an empty dictionary. -- http://mail.python.org/mailman/listinfo/python-list
Re: How do i add body to 'email.mime.multipart.MIMEMultipart' instance?
On Feb 4, 2:50 pm, srinivasan srinivas wrote: > Hi, > Could someone tell me the way to add body content to > 'email.mime.multipart.MIMEMultipart' instance? > > Thanks, > Srini excerpt from one of the modules I use: def build_body(html, text=''): text = text.strip() and text or html2text(html).encode('ascii', 'xmlcharrefreplace') body = MIMEMultipart('alternative') body.attach(MIMEText(text)) body.attach(MIMEText(html, 'html')) return body HTH Justin -- http://mail.python.org/mailman/listinfo/python-list
Re: How do i add body to email.mime.multipart.MIMEMultipart instance?
On Feb 4, 2:48 pm, srinivasan srinivas wrote: > Hi, > Could someone tell me the way to add body to the instance > email.mime.multipart.MIMEMultipart instance which has attachments? > > Thanks, msg = MIMEMultipart() msg.preamble = 'This is a multi-part message in MIME format.\n' msg.epilogue = '' body = MIMEMultipart('alternative') body.attach(MIMEText(text)) body.attach(MIMEText(html, 'html')) msg.attach(body) attachment = Message() attachment.add_header('Content-type', content_type, name=basename) attachment.add_header('Content-transfer-encoding', 'base64') attachment.add_header('Content-Disposition', 'attachment', filename=basename) attachment.set_payload(b.getvalue()) msg.attach(attachment) msg.add_header('Message-ID', generate_message_id(sender[1])) msg.add_header('Date', strftime(DATEFORMAT, gmtime())) msg.add_header('From', formataddr(sender)) msg.add_header('To', format_addresses(TOs)) msg.add_header('Cc', format_addresses(CCs)) msg.add_header('Subject', subj) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert between Japanese coding systems?
On Feb 19, 2:28 pm, Dietrich Bollmann wrote: > Are there any functions in python to convert between different Japanese > coding systems? > > I would like to convert between (at least) ISO-2022-JP, UTF-8, EUC-JP > and SJIS. I also need some function to encode / decode base64 encoded > strings. > > Example: > > email = '''[...] > Subject: > =?UTF-8?Q?romaji=E3=81=B2=E3=82=89=E3=81=8C=E3=81=AA=E3=82=AB=E3=82=BF?= > =?UTF-8?Q?=E3=82=AB=E3=83=8A=E6=BC=A2=E5=AD=97?= > [...] > Content-Type: text/plain; charset=EUC-JP > [...] > Content-Transfer-Encoding: base64 > [...] > > cm9tYWpppNKk6aSspMqlq6W/paulyrTBu/oNCg0K > > ''' > > from = contentType > to = 'utf-8' > contentUtf8 = convertCodingSystem(decodeBase64(content), from, to) > > The only problem is that I could not find any standard functionality to > convert between different Japanese coding systems. > > Thanks, > > Dietrich Bollmann import base64 ENCODINGS = ['ISO-2022-JP', 'UTF-8', 'EUC-JP', 'SJIS'] def decodeBase64(content): return base64.decodestring(content) def convertCodingSystem(s, _from, _to): unicode = s.decode(_from) return unicode.encode(_to) if __name__ == '__main__': content = 'cm9tYWpppNKk6aSspMqlq6W/paulyrTBu/oNCg0K' _from = 'EUC-JP' for _to in ENCODINGS: x = convertCodingSystem(decodeBase64(content), _from, _to) print _to, repr(x) -- http://mail.python.org/mailman/listinfo/python-list
Re: How to convert between Japanese coding systems?
import email from email.Header import decode_header from unicodedata import name as un MS = '''\ Subject: =?UTF-8?Q? romaji=E3=81=B2=E3=82=89=E3=81=8C=E3=81=AA=E3=82=AB=E3=82=BF?= Date: Thu, 19 Feb 2009 09:34:56 - MIME-Version: 1.0 Content-Type: text/plain; charset=EUC-JP Content-Transfer-Encoding: base64 cm9tYWpppNKk6aSspMqlq6W/paulyrTBu/oNCg0K ''' def get_header(msg, name): (value, charset), = decode_header(msg.get(name)) if not charset: return value return value.decode(charset) if __name__ == '__main__': msg = email.message_from_string(MS) s = get_header(msg, 'Subject') print repr(s) for c in s: try: print un(c) except ValueError: print repr(c) print e = msg.get_content_charset() b = msg.get_payload(decode=True).decode(e) print repr(b) for c in b: try: print un(c) except ValueError: print repr(c) print -- http://mail.python.org/mailman/listinfo/python-list
Re: download image from flickr.com
##compile_obj = re.compile(r'dyn.Img\(".*?",".*?",".*?","(.*?)"') compile_obj = re.compile(r'\http://mail.python.org/mailman/listinfo/python-list
Re: Sending multi-part MIME package via HTTP-POST
have you tried using the def request(self, method, url, body=None, headers={}) method instead of putrequest, endheaders, send methods? where body is --===1845688244== Content-Type: application/vnd.cip4-jmf+xml MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-ID: beginning --===1845688244==-- -- http://mail.python.org/mailman/listinfo/python-list
Re: file tell in a for-loop
On Nov 19, 7:00 am, Magdoll <[EMAIL PROTECTED]> wrote: > I was trying to map various locations in a file to a dictionary. At > first I read through the file using a for-loop, but tell() gave back > weird results, so I switched to while, then it worked. > > The for-loop version was something like: > d = {} > for line in f: > if line.startswith('>'): d[line] = f.tell() > > And the while version was: > d = {} > while 1: > line = f.readline() > if len(line) == 0: break > if line.startswith('>'): d[line] = f.tell() > > In the for-loop version, f.tell() would sometimes return the same > result multiple times consecutively, even though the for-loop > apparently progressed the file descriptor. I don't have a clue why > this happened, but I switched to while loop and then it worked. > > Does anyone have any ideas as to why this is so? > > Thanks, > Magdoll got bitten by that too a while back the for line in f reads ahead so your f.tell would not be the position of the end of the line had to use a while True loop instead also -- http://mail.python.org/mailman/listinfo/python-list
Re: Uploading a file using POST
On Mar 19, 8:50 am, Thomas Robitaille wrote: > I am trying to upload a binary file (a tar.gz file to be exact) to a > web server using POST, from within a python script. > > What I would like is essentially the equivalent of > > enctype="multipart/form-data"> > > have you seen http://code.activestate.com/recipes/146306/ -- http://mail.python.org/mailman/listinfo/python-list
Re: soap request includes a hyphenated field, don't know how to set it
On Mar 27, 3:33 pm, straycat...@yahoo.com wrote: > Working my way through suds, I have something like this: > > >>> event = client.factory.create('ns0:UserVerifiedEvent') > >>> print event > > (UserVerifiedEvent){ > event-id = None > user-verified-content[] = > domain-specific-attributes = > (MediaAttributes){ > domain-attribute[] = > } > } > >>> event.event-id = "164-251340-2009-03-12" > > SyntaxError: can't assign to operator > > Any ideas or python magic to get around this hyphen problem (and I > can't change that to event_id or the server won't recognize it.) > > Thanks, > Matthew haven't tried suds but perhaps you can try setattr(event, "event-id", "164-251340-2009-03-12") -- http://mail.python.org/mailman/listinfo/python-list
Re: Something weird about re.finditer()
On Apr 15, 4:46 pm, Gilles Ganault wrote: > re_block = re.compile('before (.+?) after',re.I|re.S|re.M) > > #Here, get web page and put it into "response" > > blocks = None > blocks = re_block.finditer(response) > if blocks == None: > print "No block found" > else: > print "Before blocks" > for block in blocks: > #Never displayed! > print "In blocks" > == > > Since "blocks" is no longer set to None after calling finditer()... > but doesn't contain a single block... what does it contain then? > > Thank you for any tip. because finditer returns a generator which in your case just happens to be empty >>> import re >>> patt = re.compile('foo') >>> gen = patt.finditer('bar') >>> gen is None False >>> gen == None False >>> gen >>> list(gen) [] >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: Handling some isolated iso-8859-1 characters
On Jun 4, 2:38 am, Daniel Mahoney <[EMAIL PROTECTED]> wrote: > I'm working on an app that's processing Usenet messages. I'm making a > connection to my NNTP feed and grabbing the headers for the groups I'm > interested in, saving the info to disk, and doing some post-processing. > I'm finding a few bizarre characters and I'm not sure how to handle them > pythonically. > > One of the lines I'm finding this problem with contains: > 137050 Cleo and I have an anouncement! "Mlle. =?iso-8859-1?Q?Ana=EFs?=" > <[EMAIL PROTECTED]> Sun, 21 Nov 2004 16:21:50 -0500 > <[EMAIL PROTECTED]> 447869 Xref: > sn-us rec.pets.cats.community:137050 > > The interesting patch is the string that reads "=?iso-8859-1?Q?Ana=EFs?=". > An HTML rendering of what this string should look would be "Anaïs". > > What I'm doing now is a brute-force substitution from the version in the > file to the HTML version. That's ugly. What's a better way to translate > that string? Or is my problem that I'm grabbing the headers from the NNTP > server incorrectly? >>> from email.Header import decode_header >>> decode_header("=?iso-8859-1?Q?Ana=EFs?=") [('Ana\xefs', 'iso-8859-1')] >>> (s, e), = decode_header("=?iso-8859-1?Q?Ana=EFs?=") >>> s 'Ana\xefs' >>> e 'iso-8859-1' >>> s.decode(e) u'Ana\xefs' >>> import unicodedata >>> import htmlentitydefs >>> for c in s.decode(e): ... print ord(c), unicodedata.name(c) ... 65 LATIN CAPITAL LETTER A 110 LATIN SMALL LETTER N 97 LATIN SMALL LETTER A 239 LATIN SMALL LETTER I WITH DIAERESIS 115 LATIN SMALL LETTER S >>> htmlentitydefs.codepoint2name[239] 'iuml' >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: how to send a "Multiline" mail with smtplib?
perhaps change html body=MIMEText('hello,\r\n ok',_subtype='html',_charset='windows-1255') to plain body=MIMEText('hello,\r\n ok',_subtype='plain',_charset='windows-1255') -- http://mail.python.org/mailman/listinfo/python-list
Re: Newbie, list has no attribute iteritems
def handle_starttag(self, tag, attrs): # <-- attrs here is a list if 'a' != tag: self.stack.append(self.__html_start_tag(tag, attrs))# <-- attrs here is still a list return attrs = dict(attrs)# <-- now attrs is a dictionary -- http://mail.python.org/mailman/listinfo/python-list
Re: how to use subprocess.Popen execute "find" in windows
On May 6, 5:19 pm, [EMAIL PROTECTED] wrote: > In cmd, I can use find like this. > > C:\>netstat -an | find "445" > TCP0.0.0.0:4450.0.0.0:0 LISTENING > UDP0.0.0.0:445*:* > > C:\> > > And os.system is OK.>>> import os > >>> os.system('netstat -an | find "445"') > > TCP0.0.0.0:4450.0.0.0:0 LISTENING > UDP0.0.0.0:445*:* > 0 > > > > But I don't know how to use subprocess.Popen to do this. > > from subprocess import Popen, PIPE > > p1 = Popen(['netstat', '-an'], stdout = PIPE) > p2 = Popen(['find', '"445"'], stdin = p1.stdout, stdout = PIPE) > print p2.stdout.read() > > It doesn't work. > Because subprocess.Popen execute "find" like this. > > C:\>find \"445\" > 拒绝访问 - \ > > C:\> > > It adds a '\' before each '"'. > How to remove the '\'? > Thank you. cannot help with the backslashes but try findstr instead of find -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert Word .doc to Acrobat .pdf files
## this creates a postscript file which you can then convert to PDF ## using Acrobat Distiller ## ## BTW, I spent an hour trying to get this working with ## win32com.client.Dispatch ## (the save file dialog still appeared) ## Then I remembered win32com.client.dynamic.Dispatch ## ## Can somebody please explain why this happened using ## win32com.client.Dispatch? import win32com.client.dynamic if __name__ == '__main__': printer = "Adobe PDF on NE03:" docpath = r"E:\Documents and Settings\justin\Desktop\test.doc" pspath = r"E:\Documents and Settings\justin\Desktop\test.ps" word = win32com.client.dynamic.Dispatch("Word.Application") try: document = word.Documents.Open(docpath, 0, -1) try: remember = word.ActivePrinter word.ActivePrinter = printer try: document.PrintOut(Background=0, OutputFileName=pspath, PrintToFile=-1) finally: word.ActivePrinter = remember finally: document.Close(0) del document finally: word.Quit(0) del word -- http://mail.python.org/mailman/listinfo/python-list
Re: Obtaining the remote ip address
os.environ['REMOTE_ADDR'] os.environ['REMOTE_HOST'] -- http://mail.python.org/mailman/listinfo/python-list
Re: Convert Word .doc to Acrobat .pdf files
"When you create a PostScript file you have to send the host fonts. Please go to the printer properties, "Adboe PDF Settings" page and turn OFF the option "Do not send fonts to Distiller". kbperry, sorry about that. go to "Printers and Faxes" go to properties for the "Adobe PDF" printer go to the "General" tab, "Printing Preferences" button "Adobe PDF Settings" tab uncheck the "Do not send fonts..." box rune, >> "'!CreatePDFAndCloseDoc" I had Adobe 6 once and recalled it had Word macros you could call. However, when I installed Adobe 7, I could not find the macros. Perhaps it has something to do with the naming. Thanks for the post. Will check it out. -- http://mail.python.org/mailman/listinfo/python-list
Re: how to do filetransfer using usrp.
On Feb 19, 7:38 pm, sarosh wrote: > how to do filetransfer using usrp. > can i make lan interface between two computers connected to usrp each and > then transfer files (images/video) between them? > how to transfer files? > is there any example of such kind in gnuradio? > > sarosh am not sure what USRP is but a quick google found http://packages.debian.org/sid/python-usrp -- http://mail.python.org/mailman/listinfo/python-list
Re: remove element with ElementTree
On Mar 9, 11:35 am, tdan wrote: > I have been using ElementTree to write an app, and would like to > simply remove an element. > But in ElementTree, you must know both the parent and the child > element to do this. > There is no getparent() function, so I am stuck if I only have an > element. > see http://effbot.org/zone/element.htm#accessing-parents -- http://mail.python.org/mailman/listinfo/python-list
Re: SAX unicode and ascii parsing problem
can't check right now but are you sure it's the parser and not this line d.write(csv+"\n") that's failing? what is d? -- http://mail.python.org/mailman/listinfo/python-list
Re: FTP problem
'indexftp.barcap.com' only (sans the 'ftp.' prefix) allows me to connect to an FTP server >ftp indexftp.barcap.com Connected to usftp.barcap.com. 220-Connected to usftp.barcap.com. 220 FTP server ready. User (usftp.barcap.com:(none)): -- http://mail.python.org/mailman/listinfo/python-list
Re: Python DXF import library?
On Apr 20, 9:19 pm, Stodge wrote: > Is anyone aware of a Python DXF import library? I think I remember > seeing converters but so far I haven't found a library. I need to > write a tool that reads DXFs so I'm not yet sure if a converter would > be of any use. Thanks http://lmgtfy.com/?q=Python+DXF 3rd hit is a reader hosted on Google -- http://mail.python.org/mailman/listinfo/python-list
Re: automate minesweeper with python
On Jul 1, 7:39 am, Jay wrote: > I would like to create a python script that plays the Windows game > minesweeper. > > The python code logic and running minesweeper are not problems. > However, "seeing" the 1-8 in the minesweeper map and clicking on > squares is. I have no idea how to proceed. you may want to have a look at sikuli http://groups.csail.mit.edu/uid/sikuli/ -- http://mail.python.org/mailman/listinfo/python-list
Re: guessing file type
On Jul 17, 8:39 pm, VanL wrote: > Seldon wrote: > > Hello, I need to determine programmatically a file type from its > > content/extension (much like the "file" UNIX command line utility) > > > I searched for a suitable Python library module, with little luck. Do > > you know something useful ? > I've used the magic.py module by "Jason Petrone" before. http://tinyurl.com/ldho8m -- http://mail.python.org/mailman/listinfo/python-list
Re: Extracting text from html
http://tinyurl.com/kpoweq -- http://mail.python.org/mailman/listinfo/python-list
SimpleHTTPServer, external CSS, and Google Chrome
I am running "python -m SimpleHTTPServer 80" on Windows XP Pro SP 3 (Python 2.5.4) browsing http://localhost/ using IE8 and FireFox 3.6, I get blue text on red background on Google Chrome 6.0 however, I get blue text on white background placing index.htm and styles.css (see below) under IIS, I get blue text on red background for all browsers, including Google Chrome 6.0. I get exactly the same results when browsing from another machine. what's wrong? what do I need to change in SimpleHTTPServer? index.htm -- http://www.w3.org/TR/html4/strict.dtd";> your title body { color: blue; } foo bar -- styles.css -- body { background-color: red; } -- -- http://mail.python.org/mailman/listinfo/python-list
Re: SimpleHTTPServer, external CSS, and Google Chrome
On Sep 18, 2:54 am, MrJean1 wrote: > FWIW, > > There is a blue text on a red background in all 4 browsers Google > Chrome 6.0.472.59, Safari 5.0.1 (7533.17.8), FireFox 3.6.9 and IE > 6.0.2900.5512 with Python 2.7 serving that page on my Windows XP > SP 3 machine. > > /Jean > Hmm. Will download and install newer python versions to re-check then. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: SimpleHTTPServer, external CSS, and Google Chrome
LOL. twas http://bugs.python.org/issue839496 -- http://mail.python.org/mailman/listinfo/python-list
Re: I don't get why sys.exit(1) doesn't exit the while loop in the follow case
your bare except is catching the SystemExit raised by sys.exit(1) -- http://mail.python.org/mailman/listinfo/python-list
Re: Python3: Is this a bug in urllib?
On Oct 20, 12:47 am, Johannes Bauer wrote: > > >>> from urllib import request; request.URLopener().open("http://google.de";) > aren't you supposed to call read on the return value of open? i.e., request.URLopener().open("http://google.de";).read() -- http://mail.python.org/mailman/listinfo/python-list
Re: Python3: Is this a bug in urllib?
On Oct 20, 8:32 pm, Justin Ezequiel wrote: > On Oct 20, 12:47 am, Johannes Bauer wrote: > > > > > >>> from urllib import request; request.URLopener().open("http://google.de";) > > aren't you supposed to call read on the return value of open? > i.e., > .read() better yet, f = request.URLopener().open("http://google.de";) f.read() f.close() -- http://mail.python.org/mailman/listinfo/python-list
Re: Python3: Is this a bug in urllib?
''' C:\Documents and Settings\Administrator\Desktop>python wtf.py 301 Moved Permanently b' \n301 Moved\n301 Moved\nThe document has mo ved\nhttp://www.google.de/";>here.\r\n\r\n' foo 5.328 secs 301 Moved Permanently bar 241.016 secs C:\Documents and Settings\Administrator\Desktop> ''' import http.client import time def foo(): c = http.client.HTTPConnection('google.de') try: c.request('GET', '/') r = c.getresponse() try: print(r.status, r.reason) x = r.read() finally: r.close() finally: c.close() print(x) def bar(): c = http.client.HTTPConnection('google.de') try: c.request('GET', '/') r = c.getresponse() try: print(r.status, r.reason) x = r.fp.read() finally: r.fp.close() finally: c.close() s = time.time() foo() e = time.time() print('foo %.3f secs' % (e-s,)) s = time.time() bar() e = time.time() print('bar %.3f secs' % (e-s,)) -- http://mail.python.org/mailman/listinfo/python-list