title
stringlengths
10
172
question_id
int64
469
40.1M
question_body
stringlengths
22
48.2k
question_score
int64
-44
5.52k
question_date
stringlengths
20
20
answer_id
int64
497
40.1M
answer_body
stringlengths
18
33.9k
answer_score
int64
-38
8.38k
answer_date
stringlengths
20
20
tags
sequence
How do I watch a file for changes using Python?
182,197
<p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p> <p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p> <p>If anyone's done anything like this I'd be really grateful to hear how...</p> <p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p> <p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
197
2008-10-08T11:12:55Z
182,953
<p>Well after a bit of hacking of Tim Golden's script, I have the following which seems to work quite well:</p> <pre><code>import os import win32file import win32con path_to_watch = "." # look at the current directory file_to_watch = "test.txt" # look for changes to a file called test.txt def ProcessNewData( newData ): print "Text added: %s"%newData # Set up the bits we'll need for output ACTIONS = { 1 : "Created", 2 : "Deleted", 3 : "Updated", 4 : "Renamed from something", 5 : "Renamed to something" } FILE_LIST_DIRECTORY = 0x0001 hDir = win32file.CreateFile ( path_to_watch, FILE_LIST_DIRECTORY, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS, None ) # Open the file we're interested in a = open(file_to_watch, "r") # Throw away any exising log data a.read() # Wait for new data and call ProcessNewData for each new chunk that's written while 1: # Wait for a change to occur results = win32file.ReadDirectoryChangesW ( hDir, 1024, False, win32con.FILE_NOTIFY_CHANGE_LAST_WRITE, None, None ) # For each change, check to see if it's updating the file we're interested in for action, file in results: full_filename = os.path.join (path_to_watch, file) #print file, ACTIONS.get (action, "Unknown") if file == file_to_watch: newText = a.read() if newText != "": ProcessNewData( newText ) </code></pre> <p>It could probably do with a load more error checking, but for simply watching a log file and doing some processing on it before spitting it out to the screen, this works well.</p> <p>Thanks everyone for your input - great stuff!</p>
10
2008-10-08T14:05:53Z
[ "python", "file", "pywin32", "watch" ]
How do I watch a file for changes using Python?
182,197
<p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p> <p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p> <p>If anyone's done anything like this I'd be really grateful to hear how...</p> <p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p> <p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
197
2008-10-08T11:12:55Z
473,471
<p>It should not work on windows (maybe with cygwin ?), but for unix user, you should use the "fcntl" system call. Here is an example in Python. It's mostly the same code if you need to write it in C (same function names)</p> <pre><code>import time import fcntl import os import signal FNAME = "/HOME/TOTO/FILETOWATCH" def handler(signum, frame): print "File %s modified" % (FNAME,) signal.signal(signal.SIGIO, handler) fd = os.open(FNAME, os.O_RDONLY) fcntl.fcntl(fd, fcntl.F_SETSIG, 0) fcntl.fcntl(fd, fcntl.F_NOTIFY, fcntl.DN_MODIFY | fcntl.DN_CREATE | fcntl.DN_MULTISHOT) while True: time.sleep(10000) </code></pre>
20
2009-01-23T16:08:40Z
[ "python", "file", "pywin32", "watch" ]
How do I watch a file for changes using Python?
182,197
<p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p> <p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p> <p>If anyone's done anything like this I'd be really grateful to hear how...</p> <p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p> <p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
197
2008-10-08T11:12:55Z
1,867,970
<p>Here is a simplified version of Kender's code that appears to do the same trick and does not import the entire file:</p> <pre><code># Check file for new data. import time f = open(r'c:\temp\test.txt', 'r') while True: line = f.readline() if not line: time.sleep(1) print 'Nothing New' else: print 'Call Function: ', line </code></pre>
3
2009-12-08T16:09:42Z
[ "python", "file", "pywin32", "watch" ]
How do I watch a file for changes using Python?
182,197
<p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p> <p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p> <p>If anyone's done anything like this I'd be really grateful to hear how...</p> <p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p> <p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
197
2008-10-08T11:12:55Z
3,031,168
<p>Check out <a href="https://github.com/seb-m/pyinotify">pyinotify</a>.</p> <p>inotify replaces dnotify (from an earlier answer) in newer linuxes and allows file-level rather than directory-level monitoring.</p>
19
2010-06-13T05:12:49Z
[ "python", "file", "pywin32", "watch" ]
How do I watch a file for changes using Python?
182,197
<p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p> <p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p> <p>If anyone's done anything like this I'd be really grateful to hear how...</p> <p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p> <p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
197
2008-10-08T11:12:55Z
4,690,739
<p>Did you try using <a href="http://packages.python.org/watchdog/" rel="nofollow">Watchdog</a>?</p> <blockquote> <p>Python API library and shell utilities to monitor file system events.</p> <h3>Directory monitoring made easy with</h3> <ul> <li>A cross-platform API.</li> <li>A shell tool to run commands in response to directory changes.</li> </ul> <p>Get started quickly with a simple example in <a href="https://pythonhosted.org/watchdog/quickstart.html#quickstart" rel="nofollow">Quickstart</a>...</p> </blockquote>
164
2011-01-14T11:52:26Z
[ "python", "file", "pywin32", "watch" ]
How do I watch a file for changes using Python?
182,197
<p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p> <p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p> <p>If anyone's done anything like this I'd be really grateful to hear how...</p> <p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p> <p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
197
2008-10-08T11:12:55Z
5,339,877
<p>If you want a multiplatform solution, then check <a href="http://doc.qt.io/qt-4.8/qfilesystemwatcher.html" rel="nofollow">QFileSystemWatcher</a>. Here an example code (not sanitized):</p> <pre><code>from PyQt4 import QtCore @QtCore.pyqtSlot(str) def directory_changed(path): print('Directory Changed!!!') @QtCore.pyqtSlot(str) def file_changed(path): print('File Changed!!!') fs_watcher = QtCore.QFileSystemWatcher(['/path/to/files_1', '/path/to/files_2', '/path/to/files_3']) fs_watcher.connect(fs_watcher, QtCore.SIGNAL('directoryChanged(QString)'), directory_changed) fs_watcher.connect(fs_watcher, QtCore.SIGNAL('fileChanged(QString)'), file_changed) </code></pre>
41
2011-03-17T13:45:31Z
[ "python", "file", "pywin32", "watch" ]
How do I watch a file for changes using Python?
182,197
<p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p> <p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p> <p>If anyone's done anything like this I'd be really grateful to hear how...</p> <p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p> <p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
197
2008-10-08T11:12:55Z
15,071,134
<p>This is another modification of Tim Goldan's script that runs on linux and adds a simple watcher for file modification by using a dict (file=>time).</p> <p>usage: whateverName.py path_to_dir_to_watch</p> <pre><code>#!/usr/bin/env python import os, sys, time def files_to_timestamp(path): files = [os.path.join(path, f) for f in os.listdir(path)] return dict ([(f, os.path.getmtime(f)) for f in files]) if __name__ == "__main__": path_to_watch = sys.argv[1] print "Watching ", path_to_watch before = files_to_timestamp(path_to_watch) while 1: time.sleep (2) after = files_to_timestamp(path_to_watch) added = [f for f in after.keys() if not f in before.keys()] removed = [f for f in before.keys() if not f in after.keys()] modified = [] for f in before.keys(): if not f in removed: if os.path.getmtime(f) != before.get(f): modified.append(f) if added: print "Added: ", ", ".join(added) if removed: print "Removed: ", ", ".join(removed) if modified: print "Modified ", ", ".join(modified) before = after </code></pre>
3
2013-02-25T16:05:07Z
[ "python", "file", "pywin32", "watch" ]
How do I watch a file for changes using Python?
182,197
<p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p> <p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p> <p>If anyone's done anything like this I'd be really grateful to hear how...</p> <p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p> <p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
197
2008-10-08T11:12:55Z
18,947,445
<pre><code>ACTIONS = { 1 : "Created", 2 : "Deleted", 3 : "Updated", 4 : "Renamed from something", 5 : "Renamed to something" } FILE_LIST_DIRECTORY = 0x0001 class myThread (threading.Thread): def __init__(self, threadID, fileName, directory, origin): threading.Thread.__init__(self) self.threadID = threadID self.fileName = fileName self.daemon = True self.dir = directory self.originalFile = origin def run(self): startMonitor(self.fileName, self.dir, self.originalFile) def startMonitor(fileMonitoring,dirPath,originalFile): hDir = win32file.CreateFile ( dirPath, FILE_LIST_DIRECTORY, win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE, None, win32con.OPEN_EXISTING, win32con.FILE_FLAG_BACKUP_SEMANTICS, None ) # Wait for new data and call ProcessNewData for each new chunk that's # written while 1: # Wait for a change to occur results = win32file.ReadDirectoryChangesW ( hDir, 1024, False, win32con.FILE_NOTIFY_CHANGE_LAST_WRITE, None, None ) # For each change, check to see if it's updating the file we're # interested in for action, file_M in results: full_filename = os.path.join (dirPath, file_M) #print file, ACTIONS.get (action, "Unknown") if len(full_filename) == len(fileMonitoring) and action == 3: #copy to main file ... </code></pre>
1
2013-09-22T18:40:48Z
[ "python", "file", "pywin32", "watch" ]
How do I watch a file for changes using Python?
182,197
<p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p> <p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p> <p>If anyone's done anything like this I'd be really grateful to hear how...</p> <p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p> <p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
197
2008-10-08T11:12:55Z
23,181,354
<p>This is an example of checking a file for changes. One that may not be the best way of doing it, but it sure is a short way.</p> <p>Handy tool for restarting application when changes have been made to the source. I made this when playing with pygame so I can see effects take place immediately after file save.</p> <p>When used in pygame make sure the stuff in the 'while' loop is placed in your game loop aka update or whatever. Otherwise your application will get stuck in an infinite loop and you will not see your game updating.</p> <pre><code>file_size_stored = os.stat('neuron.py').st_size while True: try: file_size_current = os.stat('neuron.py').st_size if file_size_stored != file_size_current: restart_program() except: pass </code></pre> <p>In case you wanted the restart code which I found on the web. Here it is. (Not relevant to the question, though it could come in handy)</p> <pre><code>def restart_program(): #restart application python = sys.executable os.execl(python, python, * sys.argv) </code></pre> <p>Have fun making electrons do what you want them to do.</p>
0
2014-04-20T11:11:19Z
[ "python", "file", "pywin32", "watch" ]
How do I watch a file for changes using Python?
182,197
<p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p> <p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p> <p>If anyone's done anything like this I'd be really grateful to hear how...</p> <p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p> <p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
197
2008-10-08T11:12:55Z
24,410,417
<p>Simplest solution for me is using watchdog's tool watchmedo</p> <p>From <a href="https://pypi.python.org/pypi/watchdog" rel="nofollow">https://pypi.python.org/pypi/watchdog</a> I now have a process that looks up the sql files in a directory and executes them if necessary. </p> <pre><code>watchmedo shell-command \ --patterns="*.sql" \ --recursive \ --command='~/Desktop/load_files_into_mysql_database.sh' \ . </code></pre>
4
2014-06-25T13:43:37Z
[ "python", "file", "pywin32", "watch" ]
How do I watch a file for changes using Python?
182,197
<p>I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.</p> <p>What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the <code>win32file.FindNextChangeNotification</code> function but have no idea how to ask it to watch a specific file.</p> <p>If anyone's done anything like this I'd be really grateful to hear how...</p> <p><strong>[Edit]</strong> I should have mentioned that I was after a solution that doesn't require polling.</p> <p><strong>[Edit]</strong> Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.</p>
197
2008-10-08T11:12:55Z
39,606,320
<p>Here's an example geared toward watching input files that write no more than one line per second but usually a lot less. The goal is to append the last line (most recent write) to the specified output file. I've copied this from one of my projects and just deleted all the irrelevant lines. You'll have to fill in or change the missing symbols. </p> <pre><code>from PyQt5.QtCore import QFileSystemWatcher, QSettings, QThread from ui_main_window import Ui_MainWindow # Qt Creator gen'd class MainWindow(QMainWindow, Ui_MainWindow): def __init__(self, parent=None): QMainWindow.__init__(self, parent) Ui_MainWindow.__init__(self) self._fileWatcher = QFileSystemWatcher() self._fileWatcher.fileChanged.connect(self.fileChanged) def fileChanged(self, filepath): QThread.msleep(300) # Reqd on some machines, give chance for write to complete # ^^ About to test this, may need more sophisticated solution with open(filepath) as file: lastLine = list(file)[-1] destPath = self._filemap[filepath]['dest file'] with open(destPath, 'a') as out_file: # a= append out_file.writelines([lastLine]) </code></pre> <p>Of course, the encompassing QMainWindow class is not strictly required, ie. you can use QFileSystemWatcher alone. </p>
0
2016-09-21T01:53:44Z
[ "python", "file", "pywin32", "watch" ]
What do I need to import to gain access to my models?
182,229
<p>I'd like to run a script to populate my database. I'd like to access it through the Django database API.</p> <p>The only problem is that I don't know what I would need to import to gain access to this.</p> <p>How can this be achieved?</p>
7
2008-10-08T11:23:54Z
182,275
<p>In addition to your own models files, you need to import your settings module as well.</p>
0
2008-10-08T11:37:18Z
[ "python", "django" ]
What do I need to import to gain access to my models?
182,229
<p>I'd like to run a script to populate my database. I'd like to access it through the Django database API.</p> <p>The only problem is that I don't know what I would need to import to gain access to this.</p> <p>How can this be achieved?</p>
7
2008-10-08T11:23:54Z
182,345
<p>Import your settings module too</p> <pre><code>import os os.environ["DJANGO_SETTINGS_MODULE"] = "mysite.settings" from mysite.polls.models import Poll, Choice </code></pre> <p>should do the trick.</p>
12
2008-10-08T11:55:46Z
[ "python", "django" ]
What do I need to import to gain access to my models?
182,229
<p>I'd like to run a script to populate my database. I'd like to access it through the Django database API.</p> <p>The only problem is that I don't know what I would need to import to gain access to this.</p> <p>How can this be achieved?</p>
7
2008-10-08T11:23:54Z
182,790
<p>If you use the <code>shell</code> argument to the <code>manage.py</code> script in your project directory, you don't have to import the settings manually:</p> <pre><code>$ cd mysite/ $ ./manage.py shell Python 2.5.2 (r252:60911, Jun 10 2008, 10:35:34) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. &gt;&gt;&gt; from myapp.models import * &gt;&gt;&gt; </code></pre> <p>For non-interactive use you could implement a <a href="http://docs.djangoproject.com/en/dev/howto/custom-management-commands/" rel="nofollow">custom command</a> and run it with <code>manage.py</code>.</p>
5
2008-10-08T13:38:07Z
[ "python", "django" ]
What do I need to import to gain access to my models?
182,229
<p>I'd like to run a script to populate my database. I'd like to access it through the Django database API.</p> <p>The only problem is that I don't know what I would need to import to gain access to this.</p> <p>How can this be achieved?</p>
7
2008-10-08T11:23:54Z
184,898
<p>This is what I have at the top of one my data loading scripts.</p> <pre><code>import string import sys try: import settings # Assumed to be in the same directory. #settings.DISABLE_TRANSACTION_MANAGEMENT = True except ImportError: sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__) sys.exit(1) #Setup the django environment with the settings module. import django import django.core.management django.core.management.setup_environ(settings) from django.db import transaction </code></pre> <p>This should all execute before you do much else in your script.</p> <p>Another method is to use fixtures and manage.py. Though if you are just trying to accomplish a bulk data load to initialize a database this should work fine.</p> <p>Also depending on what you are doing you may or may not want to do it all in one transaction. Uncomment the transaction line above and structure your code similar to this.</p> <pre><code>transaction.enter_transaction_management() try: #Do some stuff transaction.commit() finally: transaction.rollback() pass transaction.leave_transaction_management() </code></pre>
6
2008-10-08T21:00:46Z
[ "python", "django" ]
What do I need to import to gain access to my models?
182,229
<p>I'd like to run a script to populate my database. I'd like to access it through the Django database API.</p> <p>The only problem is that I don't know what I would need to import to gain access to this.</p> <p>How can this be achieved?</p>
7
2008-10-08T11:23:54Z
7,870,288
<p>The cleanest solution is to add django extensions.</p> <pre> (virt1)tsmets@calvin:~/Documents/prive/rugby-club/proposal/kitu$ yolk -l Django - 1.3.1 - active Pygments - 1.4 - active Python - 2.6.5 - active development (/usr/lib/python2.6/lib-dynload) django-extensions - 0.7.1 - active pip - 1.0.2 - active setuptools - 0.6c11 - active wsgiref - 0.1.2 - active development (/usr/lib/python2.6) yolk - 0.4.1 - active </pre> <p>The list of possible commands is then extended with among other things the runscript command.</p>
1
2011-10-24T00:21:03Z
[ "python", "django" ]
Os.path : can you explain this behavior?
182,253
<p>I love Python because it comes batteries included, and I use built-in functions, a lot, to do the dirty job for me.</p> <p>I have always been using happily the os.path module to deal with file path but recently I ended up with unexpected results on Python 2.5 under Ubuntu linux, while dealing with string that represent windows file paths :</p> <pre><code>filepath = r"c:\ttemp\FILEPA~1.EXE" print os.path.basename(filepath) 'c:\\ttemp\\FILEPA~1.EXE'] print os.path.splitdrive(filepath) ('', 'c:\ttemp\\FILEPA~1.EXE') </code></pre> <p>WTF ?</p> <p>It ends up the same way with filepath = u"c:\ttemp\FILEPA~1.EXE" and filepath = "c:\ttemp\FILEPA~1.EXE".</p> <p>Do you have a clue ? Ubuntu use UTF8 but I don't feel like it has something to do with it. Maybe my Python install is messed up but I did not perform any particular tweak on it that I can remember.</p>
5
2008-10-08T11:32:16Z
182,282
<p>From a <code>os.path</code> documentation:</p> <p><strong>os.path.splitdrive(path)</strong><br /> Split the pathname path into a pair (drive, tail) where drive is either a drive specification or the empty string. On systems which do not use drive specifications, drive will always be the empty string. In all cases, drive + tail will be the same as path.</p> <p>If you running this on unix, it doesnt use drive specifications, hence - drive will be empty string. </p> <p>If you want to solve windows paths on any platform, you can just use a simple regexp:</p> <pre><code>import re (drive, tail) = re.compile('([a-zA-Z]\:){0,1}(.*)').match(filepath).groups() </code></pre> <p><code>drive</code> will be a drive letter followed by <code>:</code> (eg. <code>c:</code>, <code>u:</code>) or <code>None</code>, and <code>tail</code> the whole rest :)</p>
3
2008-10-08T11:38:57Z
[ "python", "path" ]
Os.path : can you explain this behavior?
182,253
<p>I love Python because it comes batteries included, and I use built-in functions, a lot, to do the dirty job for me.</p> <p>I have always been using happily the os.path module to deal with file path but recently I ended up with unexpected results on Python 2.5 under Ubuntu linux, while dealing with string that represent windows file paths :</p> <pre><code>filepath = r"c:\ttemp\FILEPA~1.EXE" print os.path.basename(filepath) 'c:\\ttemp\\FILEPA~1.EXE'] print os.path.splitdrive(filepath) ('', 'c:\ttemp\\FILEPA~1.EXE') </code></pre> <p>WTF ?</p> <p>It ends up the same way with filepath = u"c:\ttemp\FILEPA~1.EXE" and filepath = "c:\ttemp\FILEPA~1.EXE".</p> <p>Do you have a clue ? Ubuntu use UTF8 but I don't feel like it has something to do with it. Maybe my Python install is messed up but I did not perform any particular tweak on it that I can remember.</p>
5
2008-10-08T11:32:16Z
182,283
<p>See the documentation <a href="http://pydoc.org/2.5.1/posixpath.html" rel="nofollow">here</a>, specifically: </p> <blockquote> <p>splitdrive(p) Split a pathname into drive and path. <strong>On Posix, drive is always empty.</strong></p> </blockquote> <p>So this won't work on a Linux box.</p>
1
2008-10-08T11:39:03Z
[ "python", "path" ]
Os.path : can you explain this behavior?
182,253
<p>I love Python because it comes batteries included, and I use built-in functions, a lot, to do the dirty job for me.</p> <p>I have always been using happily the os.path module to deal with file path but recently I ended up with unexpected results on Python 2.5 under Ubuntu linux, while dealing with string that represent windows file paths :</p> <pre><code>filepath = r"c:\ttemp\FILEPA~1.EXE" print os.path.basename(filepath) 'c:\\ttemp\\FILEPA~1.EXE'] print os.path.splitdrive(filepath) ('', 'c:\ttemp\\FILEPA~1.EXE') </code></pre> <p>WTF ?</p> <p>It ends up the same way with filepath = u"c:\ttemp\FILEPA~1.EXE" and filepath = "c:\ttemp\FILEPA~1.EXE".</p> <p>Do you have a clue ? Ubuntu use UTF8 but I don't feel like it has something to do with it. Maybe my Python install is messed up but I did not perform any particular tweak on it that I can remember.</p>
5
2008-10-08T11:32:16Z
182,417
<p>If you want to manipulate Windows paths on linux you should use the ntpath module (this is the module that is imported as os.path on windows - posixpath is imported as os.path on linux)</p> <pre><code>&gt;&gt;&gt; import ntpath &gt;&gt;&gt; filepath = r"c:\ttemp\FILEPA~1.EXE" &gt;&gt;&gt; print ntpath.basename(filepath) FILEPA~1.EXE &gt;&gt;&gt; print ntpath.splitdrive(filepath) ('c:', '\\ttemp\\FILEPA~1.EXE') </code></pre>
24
2008-10-08T12:11:55Z
[ "python", "path" ]
How can I use UUIDs in SQLAlchemy?
183,042
<p>Is there a way to define a column (primary key) as a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier">UUID</a> in <a href="http://www.sqlalchemy.org/">SQLAlchemy</a> if using <a href="http://www.postgresql.org/">PostgreSQL</a> (Postgres)?</p>
26
2008-10-08T14:26:20Z
188,427
<p>You could try writing a <a href="http://www.sqlalchemy.org/docs/05/types.html#types_custom" rel="nofollow">custom type</a>, for instance:</p> <pre><code>import sqlalchemy.types as types class UUID(types.TypeEngine): def get_col_spec(self): return "uuid" def bind_processor(self, dialect): def process(value): return value return process def result_processor(self, dialect): def process(value): return value return process table = Table('foo', meta, Column('id', UUID(), primary_key=True), ) </code></pre>
-15
2008-10-09T18:01:58Z
[ "python", "postgresql", "orm", "sqlalchemy", "uuid" ]
How can I use UUIDs in SQLAlchemy?
183,042
<p>Is there a way to define a column (primary key) as a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier">UUID</a> in <a href="http://www.sqlalchemy.org/">SQLAlchemy</a> if using <a href="http://www.postgresql.org/">PostgreSQL</a> (Postgres)?</p>
26
2008-10-08T14:26:20Z
812,363
<p><a href="http://blog.sadphaeton.com/2009/01/19/sqlalchemy-recipeuuid-column.html" rel="nofollow">I wrote this</a> and the domain is gone but here's the guts....</p> <p>Regardless of how my colleagues who really care about proper database design feel about UUID's and GUIDs used for key fields. I often find I need to do it. I think it has some advantages over autoincrement that make it worth it. </p> <p>I've been refining a UUID column type for the past few months and I think I've finally got it solid.</p> <pre><code>from sqlalchemy import types from sqlalchemy.dialects.mysql.base import MSBinary from sqlalchemy.schema import Column import uuid class UUID(types.TypeDecorator): impl = MSBinary def __init__(self): self.impl.length = 16 types.TypeDecorator.__init__(self,length=self.impl.length) def process_bind_param(self,value,dialect=None): if value and isinstance(value,uuid.UUID): return value.bytes elif value and not isinstance(value,uuid.UUID): raise ValueError,'value %s is not a valid uuid.UUID' % value else: return None def process_result_value(self,value,dialect=None): if value: return uuid.UUID(bytes=value) else: return None def is_mutable(self): return False id_column_name = "id" def id_column(): import uuid return Column(id_column_name,UUID(),primary_key=True,default=uuid.uuid4) # Usage my_table = Table('test', metadata, id_column(), Column('parent_id', UUID(), ForeignKey(table_parent.c.id))) </code></pre> <p>I believe storing as binary(16 bytes) should end up being more efficient than the string representation(36 bytes?), And there seems to be some indication that indexing 16 byte blocks should be more efficient in mysql than strings. I wouldn't expect it to be worse anyway.</p> <p>One disadvantage I've found is that at least in phpymyadmin, you can't edit records because it implicitly tries to do some sort of character conversion for the "select * from table where id =..." and there's miscellaneous display issues.</p> <p>Other than that everything seems to work fine, and so I'm throwing it out there. Leave a comment if you see a glaring error with it. I welcome any suggestions for improving it.</p> <p>Unless I'm missing something the above solution will work if the underlying database has a UUID type. If it doesn't, you would likely get errors when the table is created. The solution I came up with I was targeting MSSqlServer originally and then went MySql in the end, so I think my solution is a little more flexible as it seems to work fine on mysql and sqlite. Haven't bothered checking postgres yet. </p>
40
2009-05-01T17:29:48Z
[ "python", "postgresql", "orm", "sqlalchemy", "uuid" ]
How can I use UUIDs in SQLAlchemy?
183,042
<p>Is there a way to define a column (primary key) as a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier">UUID</a> in <a href="http://www.sqlalchemy.org/">SQLAlchemy</a> if using <a href="http://www.postgresql.org/">PostgreSQL</a> (Postgres)?</p>
26
2008-10-08T14:26:20Z
5,384,215
<p>See also the recipe for <a href="http://docs.sqlalchemy.org/en/rel_0_9/core/custom_types.html?highlight=guid#backend-agnostic-guid-type" rel="nofollow">Backend-agnostic GUID Type</a> in the SQLAlchemy documentation for column types.</p>
21
2011-03-21T21:51:55Z
[ "python", "postgresql", "orm", "sqlalchemy", "uuid" ]
How can I use UUIDs in SQLAlchemy?
183,042
<p>Is there a way to define a column (primary key) as a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier">UUID</a> in <a href="http://www.sqlalchemy.org/">SQLAlchemy</a> if using <a href="http://www.postgresql.org/">PostgreSQL</a> (Postgres)?</p>
26
2008-10-08T14:26:20Z
10,301,680
<p>Unfortunately <a href="http://docs.sqlalchemy.org/en/rel_0_9/core/custom_types.html?highlight=guid#backend-agnostic-guid-type" rel="nofollow">Backend-agnostic GUID Type</a> from the SQLAlchemy documentation for column types does not seem to work for primary keys in SQLite database engines. Not quite as ecumenical as I was hoping for.</p>
4
2012-04-24T16:04:33Z
[ "python", "postgresql", "orm", "sqlalchemy", "uuid" ]
How can I use UUIDs in SQLAlchemy?
183,042
<p>Is there a way to define a column (primary key) as a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier">UUID</a> in <a href="http://www.sqlalchemy.org/">SQLAlchemy</a> if using <a href="http://www.postgresql.org/">PostgreSQL</a> (Postgres)?</p>
26
2008-10-08T14:26:20Z
19,935,248
<p>In case anyone is interested, I've been using Tom Willis answer, but found useful to add a string to uuid.UUID conversion in the process_bind_param method</p> <pre><code>class UUID(types.TypeDecorator): impl = types.LargeBinary def __init__(self): self.impl.length = 16 types.TypeDecorator.__init__(self, length=self.impl.length) def process_bind_param(self, value, dialect=None): if value and isinstance(value, uuid.UUID): return value.bytes elif value and isinstance(value, basestring): return uuid.UUID(value).bytes elif value: raise ValueError('value %s is not a valid uuid.UUId' % value) else: return None def process_result_value(self, value, dialect=None): if value: return uuid.UUID(bytes=value) else: return None def is_mutable(self): return False </code></pre>
2
2013-11-12T16:57:36Z
[ "python", "postgresql", "orm", "sqlalchemy", "uuid" ]
How can I use UUIDs in SQLAlchemy?
183,042
<p>Is there a way to define a column (primary key) as a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier">UUID</a> in <a href="http://www.sqlalchemy.org/">SQLAlchemy</a> if using <a href="http://www.postgresql.org/">PostgreSQL</a> (Postgres)?</p>
26
2008-10-08T14:26:20Z
30,604,002
<p>Here is an approach based on the <a href="http://docs.sqlalchemy.org/en/rel_0_9/core/custom_types.html?highlight=guid#backend-agnostic-guid-type" rel="nofollow">Backend agnostic GUID</a> from the SQLAlchemy docs, but using a BINARY field to store the UUIDs in non-postgresql databases.</p> <pre><code>import uuid from sqlalchemy.types import TypeDecorator, BINARY from sqlalchemy.dialects.postgresql import UUID as psqlUUID class UUID(TypeDecorator): """Platform-independent GUID type. Uses Postgresql's UUID type, otherwise uses BINARY(16), to store UUID. """ impl = BINARY def load_dialect_impl(self, dialect): if dialect.name == 'postgresql': return dialect.type_descriptor(psqlUUID()) else: return dialect.type_descriptor(BINARY(16)) def process_bind_param(self, value, dialect): if value is None: return value else: if not isinstance(value, uuid.UUID): if isinstance(value, bytes): value = uuid.UUID(bytes=value) elif isinstance(value, int): value = uuid.UUID(int=value) elif isinstance(value, str): value = uuid.UUID(value) if dialect.name == 'postgresql': return str(value) else: return value.bytes def process_result_value(self, value, dialect): if value is None: return value if dialect.name == 'postgresql': return uuid.UUID(value) else: return uuid.UUID(bytes=value) </code></pre>
1
2015-06-02T18:39:59Z
[ "python", "postgresql", "orm", "sqlalchemy", "uuid" ]
How can I use UUIDs in SQLAlchemy?
183,042
<p>Is there a way to define a column (primary key) as a <a href="https://en.wikipedia.org/wiki/Universally_unique_identifier">UUID</a> in <a href="http://www.sqlalchemy.org/">SQLAlchemy</a> if using <a href="http://www.postgresql.org/">PostgreSQL</a> (Postgres)?</p>
26
2008-10-08T14:26:20Z
32,332,765
<p>I've used the <code>UUIDType</code> from the <code>SQLAlchemy-Utils</code> package: <a href="http://sqlalchemy-utils.readthedocs.org/en/latest/data_types.html#module-sqlalchemy_utils.types.uuid" rel="nofollow">http://sqlalchemy-utils.readthedocs.org/en/latest/data_types.html#module-sqlalchemy_utils.types.uuid</a></p>
4
2015-09-01T13:20:16Z
[ "python", "postgresql", "orm", "sqlalchemy", "uuid" ]
Is this the best way to get unique version of filename w/ Python?
183,480
<p>Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there is a better way to do this? Thanks!</p> <pre><code>def unique_filename(file_name): counter = 1 file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext') while os.path.isfile(file_name): file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1] counter += 1 return file_name </code></pre> <p>I really <em>do</em> require the files to be in a single directory, and numbering duplicates is definitely acceptable in my case, so I'm not looking for a more robust method (tho' I suppose any pointers are welcome), but just to make sure that what this accomplishes is getting done the right way.</p>
13
2008-10-08T15:50:21Z
183,492
<p>If you want readable names this looks like a good solution.<br /> There are routines to return unique file names for eg. temp files but they produce long random looking names.</p>
1
2008-10-08T15:52:38Z
[ "python", "filenames" ]
Is this the best way to get unique version of filename w/ Python?
183,480
<p>Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there is a better way to do this? Thanks!</p> <pre><code>def unique_filename(file_name): counter = 1 file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext') while os.path.isfile(file_name): file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1] counter += 1 return file_name </code></pre> <p>I really <em>do</em> require the files to be in a single directory, and numbering duplicates is definitely acceptable in my case, so I'm not looking for a more robust method (tho' I suppose any pointers are welcome), but just to make sure that what this accomplishes is getting done the right way.</p>
13
2008-10-08T15:50:21Z
183,528
<p>Two small changes...</p> <pre><code>base_name, ext = os.path.splitext(file_name) </code></pre> <p>You get two results with distinct meaning, give them distinct names.</p> <pre><code>file_name = "%s_%d%s" % (base_name, str(counter), ext) </code></pre> <p>It isn't faster or significantly shorter. But, when you want to change your file name pattern, the pattern is on one place, and slightly easier to work with.</p>
2
2008-10-08T16:00:51Z
[ "python", "filenames" ]
Is this the best way to get unique version of filename w/ Python?
183,480
<p>Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there is a better way to do this? Thanks!</p> <pre><code>def unique_filename(file_name): counter = 1 file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext') while os.path.isfile(file_name): file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1] counter += 1 return file_name </code></pre> <p>I really <em>do</em> require the files to be in a single directory, and numbering duplicates is definitely acceptable in my case, so I'm not looking for a more robust method (tho' I suppose any pointers are welcome), but just to make sure that what this accomplishes is getting done the right way.</p>
13
2008-10-08T15:50:21Z
183,533
<p>Yes, this is a good strategy for readable but unique filenames.</p> <p><strong>One important change</strong>: You should replace <code>os.path.isfile</code> with <code>os.path.lexists</code>! As it is written right now, if there is a directory named /foo/bar.baz, your program will try to overwrite that with the new file (which won't work)... since <code>isfile</code> only checks for files and not directories. <code>lexists</code> checks for directories, symlinks, etc... basically if there's any reason that filename could not be created.</p> <p>EDIT: @Brian gave a better answer, which is more secure and robust in terms of race conditions.</p>
6
2008-10-08T16:02:08Z
[ "python", "filenames" ]
Is this the best way to get unique version of filename w/ Python?
183,480
<p>Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there is a better way to do this? Thanks!</p> <pre><code>def unique_filename(file_name): counter = 1 file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext') while os.path.isfile(file_name): file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1] counter += 1 return file_name </code></pre> <p>I really <em>do</em> require the files to be in a single directory, and numbering duplicates is definitely acceptable in my case, so I'm not looking for a more robust method (tho' I suppose any pointers are welcome), but just to make sure that what this accomplishes is getting done the right way.</p>
13
2008-10-08T15:50:21Z
183,582
<p>One issue is that there is a race condition in your above code, since there is a gap between testing for existance, and creating the file. There may be security implications to this (think about someone maliciously inserting a symlink to a sensitive file which they wouldn't be able to overwrite, but your program running with a higher privilege could) Attacks like these are why things like os.tempnam() are deprecated.</p> <p>To get around it, the best approach is to actually try create the file in such a way that you'll get an exception if it fails, and on success, return the actually opened file object. This can be done with the lower level os.open functions, by passing both the os.O_CREAT and os.O_EXCL flags. Once opened, return the actual file (and optionally filename) you create. Eg, here's your code modified to use this approach (returning a (file, filename) tuple):</p> <pre><code>def unique_file(file_name): counter = 1 file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext') while 1: try: fd = os.open(file_name, os.O_CREAT | os.O_EXCL | os.O_RDRW) return os.fdopen(fd), file_name except OSError: pass file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1] counter += 1 </code></pre> <p><strong>[Edit]</strong> Actually, a better way, which will handle the above issues for you, is probably to use the tempfile module, though you may lose some control over the naming. Here's an example of using it (keeping a similar interface):</p> <pre><code>def unique_file(file_name): dirname, filename = os.path.split(file_name) prefix, suffix = os.path.splitext(filename) fd, filename = tempfile.mkstemp(suffix, prefix+"_", dirname) return os.fdopen(fd), filename &gt;&gt;&gt; f, filename=unique_file('/home/some_dir/foo.txt') &gt;&gt;&gt; print filename /home/some_dir/foo_z8f_2Z.txt </code></pre> <p>The only downside with this approach is that you will always get a filename with some random characters in it, as there's no attempt to create an unmodified file (/home/some_dir/foo.txt) first. You may also want to look at tempfile.TemporaryFile and NamedTemporaryFile, which will do the above and also automatically delete from disk when closed.</p>
22
2008-10-08T16:13:02Z
[ "python", "filenames" ]
Is this the best way to get unique version of filename w/ Python?
183,480
<p>Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there is a better way to do this? Thanks!</p> <pre><code>def unique_filename(file_name): counter = 1 file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext') while os.path.isfile(file_name): file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1] counter += 1 return file_name </code></pre> <p>I really <em>do</em> require the files to be in a single directory, and numbering duplicates is definitely acceptable in my case, so I'm not looking for a more robust method (tho' I suppose any pointers are welcome), but just to make sure that what this accomplishes is getting done the right way.</p>
13
2008-10-08T15:50:21Z
185,558
<p>if you don't care about readability, uuid.uuid4() is your friend.</p> <pre><code>import uuid def unique_filename(prefix=None, suffix=None): fn = [] if prefix: fn.extend([prefix, '-']) fn.append(str(uuid.uuid4())) if suffix: fn.extend(['.', suffix.lstrip('.')]) return ''.join(fn) </code></pre>
0
2008-10-09T01:07:49Z
[ "python", "filenames" ]
Is this the best way to get unique version of filename w/ Python?
183,480
<p>Still 'diving in' to Python, and want to make sure I'm not overlooking something. I wrote a script that extracts files from several zip files, and saves the extracted files together in one directory. To prevent duplicate filenames from being over-written, I wrote this little function - and I'm just wondering if there is a better way to do this? Thanks!</p> <pre><code>def unique_filename(file_name): counter = 1 file_name_parts = os.path.splitext(file_name) # returns ('/path/file', '.ext') while os.path.isfile(file_name): file_name = file_name_parts[0] + '_' + str(counter) + file_name_parts[1] counter += 1 return file_name </code></pre> <p>I really <em>do</em> require the files to be in a single directory, and numbering duplicates is definitely acceptable in my case, so I'm not looking for a more robust method (tho' I suppose any pointers are welcome), but just to make sure that what this accomplishes is getting done the right way.</p>
13
2008-10-08T15:50:21Z
691,029
<p>How about </p> <pre><code>def ensure_unique_filename(orig_file_path): from time import time import os if os.path.lexists(orig_file_path): name, ext = os.path.splitext(orig_file_path) orig_file_path = name + str(time()).replace('.', '') + ext return orig_file_path </code></pre> <p>time() returns current time in milliseconds. combined with original filename, it's fairly unique even in complex multithreaded cases.</p>
0
2009-03-27T18:47:16Z
[ "python", "filenames" ]
In Python, what is the difference between '/' and '//' when used for division?
183,853
<p>Is there a benefit to using one over the other? They both seem to return the same results.</p> <pre><code>&gt;&gt;&gt; 6/3 2 &gt;&gt;&gt; 6//3 2 </code></pre>
144
2008-10-08T17:16:35Z
183,863
<p><code>//</code> is floor division, it will always give you the integer floor of the result. The other is 'regular' division.</p>
0
2008-10-08T17:19:15Z
[ "python", "math", "syntax", "operators" ]
In Python, what is the difference between '/' and '//' when used for division?
183,853
<p>Is there a benefit to using one over the other? They both seem to return the same results.</p> <pre><code>&gt;&gt;&gt; 6/3 2 &gt;&gt;&gt; 6//3 2 </code></pre>
144
2008-10-08T17:16:35Z
183,865
<p>The double slash, <code>//</code>, is floor division:</p> <pre><code>&gt;&gt;&gt; 7//3 2 </code></pre>
2
2008-10-08T17:19:42Z
[ "python", "math", "syntax", "operators" ]
In Python, what is the difference between '/' and '//' when used for division?
183,853
<p>Is there a benefit to using one over the other? They both seem to return the same results.</p> <pre><code>&gt;&gt;&gt; 6/3 2 &gt;&gt;&gt; 6//3 2 </code></pre>
144
2008-10-08T17:16:35Z
183,866
<p><code>//</code> implements "floor division", regardless of your type. So <code>1.0/2.0</code> will give <code>0.5</code>, but both <code>1/2</code>, <code>1//2</code> and <code>1.0//2.0</code> will give <code>0</code>.</p> <p>See <a href="https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator">https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator</a> for details</p>
9
2008-10-08T17:19:59Z
[ "python", "math", "syntax", "operators" ]
In Python, what is the difference between '/' and '//' when used for division?
183,853
<p>Is there a benefit to using one over the other? They both seem to return the same results.</p> <pre><code>&gt;&gt;&gt; 6/3 2 &gt;&gt;&gt; 6//3 2 </code></pre>
144
2008-10-08T17:16:35Z
183,870
<p>In Python 3.0, <code>5 / 2</code> will return <code>2.5</code> and <code>5 // 2</code> will return <code>2</code>. The former is floating point division, and the latter is floor division, sometimes also called integer division.</p> <p>In Python 2.2 or later in the 2.x line, there is no difference for integers unless you perform a <code>from __future__ import division</code>, which causes Python 2.x to adopt the behavior of 3.0</p> <p>Regardless of the future import, <code>5.0 // 2</code> will return <code>2.0</code> since that's the floor division result of the operation.</p> <p>You can find a detailed description at <a href="https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator">https://docs.python.org/whatsnew/2.2.html#pep-238-changing-the-division-operator</a></p>
210
2008-10-08T17:21:37Z
[ "python", "math", "syntax", "operators" ]
In Python, what is the difference between '/' and '//' when used for division?
183,853
<p>Is there a benefit to using one over the other? They both seem to return the same results.</p> <pre><code>&gt;&gt;&gt; 6/3 2 &gt;&gt;&gt; 6//3 2 </code></pre>
144
2008-10-08T17:16:35Z
1,648,557
<p>Please refer <a href="http://python-history.blogspot.com/2009/03/problem-with-integer-division.html" rel="nofollow">The Problem with Integer Division</a> for the reason for introducing the <code>//</code> operator to do integer division.</p>
2
2009-10-30T08:10:20Z
[ "python", "math", "syntax", "operators" ]
In Python, what is the difference between '/' and '//' when used for division?
183,853
<p>Is there a benefit to using one over the other? They both seem to return the same results.</p> <pre><code>&gt;&gt;&gt; 6/3 2 &gt;&gt;&gt; 6//3 2 </code></pre>
144
2008-10-08T17:16:35Z
1,704,753
<p>As everyone has already answered, <code>//</code> is floor division.</p> <p>Why this is important is that <code>//</code> is unambiguously floor division, in all Python versions from 2.2, including Python 3.x versions.</p> <p>The behavior of <code>/</code> can change depending on:</p> <ul> <li>Active <code>__future__</code> import or not (module-local)</li> <li>Python command line option, either <code>-Q old</code> or <code>-Q new</code></li> </ul>
13
2009-11-09T23:55:18Z
[ "python", "math", "syntax", "operators" ]
In Python, what is the difference between '/' and '//' when used for division?
183,853
<p>Is there a benefit to using one over the other? They both seem to return the same results.</p> <pre><code>&gt;&gt;&gt; 6/3 2 &gt;&gt;&gt; 6//3 2 </code></pre>
144
2008-10-08T17:16:35Z
11,604,247
<p>It helps to clarify for the Python 2.x line, <code>/</code> is neither floor division nor true division. The current accepted answer is not clear on this. <code>/</code> is floor division when both args are int, but is true division when either or both of the args are float.</p> <p>The above tells a lot more truth, and is a lot more clearer than the 2nd paragraph in the accepted answer.</p>
25
2012-07-22T21:50:35Z
[ "python", "math", "syntax", "operators" ]
In Python, what is the difference between '/' and '//' when used for division?
183,853
<p>Is there a benefit to using one over the other? They both seem to return the same results.</p> <pre><code>&gt;&gt;&gt; 6/3 2 &gt;&gt;&gt; 6//3 2 </code></pre>
144
2008-10-08T17:16:35Z
22,487,879
<pre><code>&gt;&gt;&gt; print 5.0 / 2 2.5 &gt;&gt;&gt; print 5.0 // 2 2.0 </code></pre>
6
2014-03-18T18:23:48Z
[ "python", "math", "syntax", "operators" ]
In Python, what is the difference between '/' and '//' when used for division?
183,853
<p>Is there a benefit to using one over the other? They both seem to return the same results.</p> <pre><code>&gt;&gt;&gt; 6/3 2 &gt;&gt;&gt; 6//3 2 </code></pre>
144
2008-10-08T17:16:35Z
30,624,406
<p>The answer of the equation is rounded to the next smaller integer or float with .0 as decimal point. </p> <pre><code>&gt;&gt;&gt;print 5//2 2 &gt;&gt;&gt; print 5.0//2 2.0 &gt;&gt;&gt;print 5//2.0 2.0 &gt;&gt;&gt;print 5.0//2.0 2.0 </code></pre>
1
2015-06-03T15:26:43Z
[ "python", "math", "syntax", "operators" ]
In Python, what is the difference between '/' and '//' when used for division?
183,853
<p>Is there a benefit to using one over the other? They both seem to return the same results.</p> <pre><code>&gt;&gt;&gt; 6/3 2 &gt;&gt;&gt; 6//3 2 </code></pre>
144
2008-10-08T17:16:35Z
38,552,114
<p><strong>/</strong> --> Floating point division</p> <p><strong>//</strong> --> Floor division</p> <p>Lets see some examples in both python 2.7 and in Python 3.5.</p> <p>Python 2.7.10 vs. Python 3.5 </p> <pre><code>print (2/3) ----&gt; 0 print (2/3) ----&gt; 0.6666666666666666 </code></pre> <p>Python 2.7.10 vs. Python 3.5 </p> <pre><code> print (4/2) ----&gt; 2 print (4/2) ----&gt; 2.0 </code></pre> <p>Now if you want to have (in python 2.7) same output as in python 3.5, you can do the following: </p> <p>Python 2.7.10 </p> <pre><code>from __future__ import division print (2/3) ----&gt; 0.6666666666666666 print (4/2) ----&gt; 2.0 </code></pre> <p>Where as there is no differece between Floor division in both python 2.7 and in Python 3.5</p> <pre><code>138.93//3 ---&gt; 46.0 138.93//3 ---&gt; 46.0 4//3 ---&gt; 1 4//3 ---&gt; 1 </code></pre>
1
2016-07-24T12:39:19Z
[ "python", "math", "syntax", "operators" ]
Framework/Language for new web 2.0 sites (2008 and 2009)
184,049
<p>I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now:</p> <ol> <li>It is now October 2008. I want to start writing an application for January 2009. I am willing to use beta code and such but by January, I'd like a site that doesn't have 'strange' problems. With that said, if a language is simply 10% slower than another, I don't care about those things as long as the issue is linear. My main concern is developer productivity.</li> <li>I'll be using Linux, Apache, MySQL for the application.</li> <li>I want the power to do things like run scp and ftp client functions with stable libraries (I only picked those two because they're not web-related but at the same time represent pretty common network protocols that any larger app might use). Technologies like OpenID and Oauth will be used as well.</li> <li>Experienced web developers are readily available (i.e. I don't have to find people from financial companies and such).</li> <li>Whatever the choice is is common and will be around for a while.</li> <li>Here's a kicker. I'd like to be able to use advanced presentation layer tools/languages similar to HAML, SASS. I definitively want to use JQuery.</li> <li>I will be creating a Facebook app and at some point doing things like dealing with SMS messages, iPhone apps, etc...</li> </ol> <p>At this point, the choices for language are PHP (Cake,Symfony,Zend), Python (Django), Ruby (Merb). I'm really between Django and Merb at this point mostly because everybody else seems to be going that way. </p> <p>Please don't put any technologies in here that aren't made for mainstream. I know Merb is untested mostly, but their stated goal is a solid platform and it has alot of momentum behind it so I'm confident that it's workable. Please don't answer with how great Perl is or .Net.</p> <p>For Future References - these choices were already made:</p> <ul> <li>Debian (Lenny) - For converting CPU cycles into something useful. Trac</li> <li>0.11 - For Project Management Gliffy - For wireframes and such </li> <li>Google Docs/Apps - For documentation, hosted email, etc... </li> <li>Amazon ec2/S3 - For hosting, storage.</li> </ul> <p>Cheers, Adam </p>
2
2008-10-08T18:07:42Z
184,107
<p>I would go with Django, if you are comfortable with a Python solution. It's at version 1.0 now, and is maturing nicely, with a large user base and many contributors. Integrating jQuery is no problem, and I've done it without any issues.</p> <p>The only thing is, as far as I can tell, Ruby is much more popular for web development nowadays, so it's easier to find Ruby developers. I get this impression from browsing recent job advertisements - there aren't that many for Python or Django. I don't know much about Merb, so I can't give a fair comparison.</p> <p>I've done enough PHP to not recommend starting a new project with it.</p>
4
2008-10-08T18:19:25Z
[ "python", "ruby-on-rails", "django", "merb" ]
Framework/Language for new web 2.0 sites (2008 and 2009)
184,049
<p>I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now:</p> <ol> <li>It is now October 2008. I want to start writing an application for January 2009. I am willing to use beta code and such but by January, I'd like a site that doesn't have 'strange' problems. With that said, if a language is simply 10% slower than another, I don't care about those things as long as the issue is linear. My main concern is developer productivity.</li> <li>I'll be using Linux, Apache, MySQL for the application.</li> <li>I want the power to do things like run scp and ftp client functions with stable libraries (I only picked those two because they're not web-related but at the same time represent pretty common network protocols that any larger app might use). Technologies like OpenID and Oauth will be used as well.</li> <li>Experienced web developers are readily available (i.e. I don't have to find people from financial companies and such).</li> <li>Whatever the choice is is common and will be around for a while.</li> <li>Here's a kicker. I'd like to be able to use advanced presentation layer tools/languages similar to HAML, SASS. I definitively want to use JQuery.</li> <li>I will be creating a Facebook app and at some point doing things like dealing with SMS messages, iPhone apps, etc...</li> </ol> <p>At this point, the choices for language are PHP (Cake,Symfony,Zend), Python (Django), Ruby (Merb). I'm really between Django and Merb at this point mostly because everybody else seems to be going that way. </p> <p>Please don't put any technologies in here that aren't made for mainstream. I know Merb is untested mostly, but their stated goal is a solid platform and it has alot of momentum behind it so I'm confident that it's workable. Please don't answer with how great Perl is or .Net.</p> <p>For Future References - these choices were already made:</p> <ul> <li>Debian (Lenny) - For converting CPU cycles into something useful. Trac</li> <li>0.11 - For Project Management Gliffy - For wireframes and such </li> <li>Google Docs/Apps - For documentation, hosted email, etc... </li> <li>Amazon ec2/S3 - For hosting, storage.</li> </ul> <p>Cheers, Adam </p>
2
2008-10-08T18:07:42Z
184,157
<p>Based in your reasons, I would go with Ruby. I see that you want some administration tools (scp, ftp client) and Ruby has it (net/sftp and net/ftp libraries).</p> <p>Also, there are great gems like God for monitoring your system, Vlad the Deployer for deploying, etc. And a lot of alternatives in Merb's field, just use whatever you find it's better for your needs (Thin, Mongrel, ebb, etc).</p>
2
2008-10-08T18:26:52Z
[ "python", "ruby-on-rails", "django", "merb" ]
Framework/Language for new web 2.0 sites (2008 and 2009)
184,049
<p>I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now:</p> <ol> <li>It is now October 2008. I want to start writing an application for January 2009. I am willing to use beta code and such but by January, I'd like a site that doesn't have 'strange' problems. With that said, if a language is simply 10% slower than another, I don't care about those things as long as the issue is linear. My main concern is developer productivity.</li> <li>I'll be using Linux, Apache, MySQL for the application.</li> <li>I want the power to do things like run scp and ftp client functions with stable libraries (I only picked those two because they're not web-related but at the same time represent pretty common network protocols that any larger app might use). Technologies like OpenID and Oauth will be used as well.</li> <li>Experienced web developers are readily available (i.e. I don't have to find people from financial companies and such).</li> <li>Whatever the choice is is common and will be around for a while.</li> <li>Here's a kicker. I'd like to be able to use advanced presentation layer tools/languages similar to HAML, SASS. I definitively want to use JQuery.</li> <li>I will be creating a Facebook app and at some point doing things like dealing with SMS messages, iPhone apps, etc...</li> </ol> <p>At this point, the choices for language are PHP (Cake,Symfony,Zend), Python (Django), Ruby (Merb). I'm really between Django and Merb at this point mostly because everybody else seems to be going that way. </p> <p>Please don't put any technologies in here that aren't made for mainstream. I know Merb is untested mostly, but their stated goal is a solid platform and it has alot of momentum behind it so I'm confident that it's workable. Please don't answer with how great Perl is or .Net.</p> <p>For Future References - these choices were already made:</p> <ul> <li>Debian (Lenny) - For converting CPU cycles into something useful. Trac</li> <li>0.11 - For Project Management Gliffy - For wireframes and such </li> <li>Google Docs/Apps - For documentation, hosted email, etc... </li> <li>Amazon ec2/S3 - For hosting, storage.</li> </ul> <p>Cheers, Adam </p>
2
2008-10-08T18:07:42Z
184,278
<p>Sorry, but your question is wrong. People are probably going to vote me down for this one but I want to say it anyway:</p> <p>I wouldn't expect to get an objective answer! Why? That's simple:</p> <ul> <li>All Ruby advocates will tell to use Ruby.</li> <li>All Python advocates will tell to use Python.</li> <li>All PHP advocates will tell to use PHP.</li> <li>Insert additional languages here.</li> </ul> <p>Got the idea?</p> <p>I recommend you to try each of the languages you mentioned for yourself. At least a few days each. Afterwards you should have a much better foundation to make your final decision.</p> <p>That said, I would choose Ruby (because I am a Ruby advocate).</p>
9
2008-10-08T18:51:26Z
[ "python", "ruby-on-rails", "django", "merb" ]
Framework/Language for new web 2.0 sites (2008 and 2009)
184,049
<p>I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now:</p> <ol> <li>It is now October 2008. I want to start writing an application for January 2009. I am willing to use beta code and such but by January, I'd like a site that doesn't have 'strange' problems. With that said, if a language is simply 10% slower than another, I don't care about those things as long as the issue is linear. My main concern is developer productivity.</li> <li>I'll be using Linux, Apache, MySQL for the application.</li> <li>I want the power to do things like run scp and ftp client functions with stable libraries (I only picked those two because they're not web-related but at the same time represent pretty common network protocols that any larger app might use). Technologies like OpenID and Oauth will be used as well.</li> <li>Experienced web developers are readily available (i.e. I don't have to find people from financial companies and such).</li> <li>Whatever the choice is is common and will be around for a while.</li> <li>Here's a kicker. I'd like to be able to use advanced presentation layer tools/languages similar to HAML, SASS. I definitively want to use JQuery.</li> <li>I will be creating a Facebook app and at some point doing things like dealing with SMS messages, iPhone apps, etc...</li> </ol> <p>At this point, the choices for language are PHP (Cake,Symfony,Zend), Python (Django), Ruby (Merb). I'm really between Django and Merb at this point mostly because everybody else seems to be going that way. </p> <p>Please don't put any technologies in here that aren't made for mainstream. I know Merb is untested mostly, but their stated goal is a solid platform and it has alot of momentum behind it so I'm confident that it's workable. Please don't answer with how great Perl is or .Net.</p> <p>For Future References - these choices were already made:</p> <ul> <li>Debian (Lenny) - For converting CPU cycles into something useful. Trac</li> <li>0.11 - For Project Management Gliffy - For wireframes and such </li> <li>Google Docs/Apps - For documentation, hosted email, etc... </li> <li>Amazon ec2/S3 - For hosting, storage.</li> </ul> <p>Cheers, Adam </p>
2
2008-10-08T18:07:42Z
184,282
<p><strong>Django!</strong></p> <p>Look up the DjangoCon talks on Google/Youtube - Especially "Reusable Apps" (www.youtube.com/watch?v=A-S0tqpPga4)</p> <p>I've been using Django for some time, after starting with Ruby/Rails. I found the Django Community easier to get into (nicer), the language documented with <em>excellent</em> examples, and it's modularity is awesome, especially if you're wanting to throw custom components into the mix, and not be forced to use certain things here and there.</p> <p>I'm sure there are probably ways to be just as flexible with Rails or some such, but I highly encourage you to take a long look at the Django introductions, etc, at <a href="http://www.djangoproject.com/" rel="nofollow">http://www.djangoproject.com/</a></p> <p>Eugene mentioned it's now at 1.0 - and therefore will remain a stable and backward-compatible codebase well through January 2009. </p> <p>Also, the automatic admin interfaces it builds are <em>production ready</em>, and extremely flexible. </p>
16
2008-10-08T18:51:52Z
[ "python", "ruby-on-rails", "django", "merb" ]
Framework/Language for new web 2.0 sites (2008 and 2009)
184,049
<p>I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now:</p> <ol> <li>It is now October 2008. I want to start writing an application for January 2009. I am willing to use beta code and such but by January, I'd like a site that doesn't have 'strange' problems. With that said, if a language is simply 10% slower than another, I don't care about those things as long as the issue is linear. My main concern is developer productivity.</li> <li>I'll be using Linux, Apache, MySQL for the application.</li> <li>I want the power to do things like run scp and ftp client functions with stable libraries (I only picked those two because they're not web-related but at the same time represent pretty common network protocols that any larger app might use). Technologies like OpenID and Oauth will be used as well.</li> <li>Experienced web developers are readily available (i.e. I don't have to find people from financial companies and such).</li> <li>Whatever the choice is is common and will be around for a while.</li> <li>Here's a kicker. I'd like to be able to use advanced presentation layer tools/languages similar to HAML, SASS. I definitively want to use JQuery.</li> <li>I will be creating a Facebook app and at some point doing things like dealing with SMS messages, iPhone apps, etc...</li> </ol> <p>At this point, the choices for language are PHP (Cake,Symfony,Zend), Python (Django), Ruby (Merb). I'm really between Django and Merb at this point mostly because everybody else seems to be going that way. </p> <p>Please don't put any technologies in here that aren't made for mainstream. I know Merb is untested mostly, but their stated goal is a solid platform and it has alot of momentum behind it so I'm confident that it's workable. Please don't answer with how great Perl is or .Net.</p> <p>For Future References - these choices were already made:</p> <ul> <li>Debian (Lenny) - For converting CPU cycles into something useful. Trac</li> <li>0.11 - For Project Management Gliffy - For wireframes and such </li> <li>Google Docs/Apps - For documentation, hosted email, etc... </li> <li>Amazon ec2/S3 - For hosting, storage.</li> </ul> <p>Cheers, Adam </p>
2
2008-10-08T18:07:42Z
184,376
<p>it depends.</p> <p>php - symfony is a great framework. downsides: php, wordy and directory heavy. propel gets annoying to use. upsides: php is everywhere and labor is cheap. well done framework, and good support. lots of plugins to make your life easier</p> <p>python - django is also a great framework. downsides: python programmers can be harder to find, django even harder. changing your db schema can be somewhat difficult since there are no official migrations. doesn't quite do mvc like you'd expect. upsides: does everything you need and has the great python std library and community behind it.</p> <p>ruby - i've never used merb, so I'll address rails. upsides: there is a plugin, gem, or recipe for almost anything you could want to do. easy to use. downsides: those plugins, gems, and recipes sometimes fail to work in mysterious ways. monkey patching is often evil. the community is.. vocal. opinionated software, and sometimes those opinions are wrong (<em>lack of foreign keys</em>). rails itself seems like a tower of cards waiting to explode and take hours of your life away.</p> <p>with all of that said, I'm a freelance php/symfony and ruby/rails developer. I've worked on several projects in both languages and frameworks. My latest project is in Rails solely because of ActiveMerchant. I've been looking for a reason to develop a django app for a while. If there were an ActiveMerchant like library for django, I probably would have used it.</p>
5
2008-10-08T19:08:42Z
[ "python", "ruby-on-rails", "django", "merb" ]
Framework/Language for new web 2.0 sites (2008 and 2009)
184,049
<p>I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now:</p> <ol> <li>It is now October 2008. I want to start writing an application for January 2009. I am willing to use beta code and such but by January, I'd like a site that doesn't have 'strange' problems. With that said, if a language is simply 10% slower than another, I don't care about those things as long as the issue is linear. My main concern is developer productivity.</li> <li>I'll be using Linux, Apache, MySQL for the application.</li> <li>I want the power to do things like run scp and ftp client functions with stable libraries (I only picked those two because they're not web-related but at the same time represent pretty common network protocols that any larger app might use). Technologies like OpenID and Oauth will be used as well.</li> <li>Experienced web developers are readily available (i.e. I don't have to find people from financial companies and such).</li> <li>Whatever the choice is is common and will be around for a while.</li> <li>Here's a kicker. I'd like to be able to use advanced presentation layer tools/languages similar to HAML, SASS. I definitively want to use JQuery.</li> <li>I will be creating a Facebook app and at some point doing things like dealing with SMS messages, iPhone apps, etc...</li> </ol> <p>At this point, the choices for language are PHP (Cake,Symfony,Zend), Python (Django), Ruby (Merb). I'm really between Django and Merb at this point mostly because everybody else seems to be going that way. </p> <p>Please don't put any technologies in here that aren't made for mainstream. I know Merb is untested mostly, but their stated goal is a solid platform and it has alot of momentum behind it so I'm confident that it's workable. Please don't answer with how great Perl is or .Net.</p> <p>For Future References - these choices were already made:</p> <ul> <li>Debian (Lenny) - For converting CPU cycles into something useful. Trac</li> <li>0.11 - For Project Management Gliffy - For wireframes and such </li> <li>Google Docs/Apps - For documentation, hosted email, etc... </li> <li>Amazon ec2/S3 - For hosting, storage.</li> </ul> <p>Cheers, Adam </p>
2
2008-10-08T18:07:42Z
186,738
<p>To get a feeling of where the Django ecosystem is at currently, you might want to check out</p> <ul> <li><a href="http://djangopeople.net/" rel="nofollow">djangopeople.net</a> (try <a href="http://djangopeople.net/us/ny/" rel="nofollow">djangopeople.net/us/ny</a> for New York state)</li> <li><a href="http://djangogigs.com/" rel="nofollow">djangogigs.com</a></li> </ul>
2
2008-10-09T10:55:29Z
[ "python", "ruby-on-rails", "django", "merb" ]
Framework/Language for new web 2.0 sites (2008 and 2009)
184,049
<p>I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now:</p> <ol> <li>It is now October 2008. I want to start writing an application for January 2009. I am willing to use beta code and such but by January, I'd like a site that doesn't have 'strange' problems. With that said, if a language is simply 10% slower than another, I don't care about those things as long as the issue is linear. My main concern is developer productivity.</li> <li>I'll be using Linux, Apache, MySQL for the application.</li> <li>I want the power to do things like run scp and ftp client functions with stable libraries (I only picked those two because they're not web-related but at the same time represent pretty common network protocols that any larger app might use). Technologies like OpenID and Oauth will be used as well.</li> <li>Experienced web developers are readily available (i.e. I don't have to find people from financial companies and such).</li> <li>Whatever the choice is is common and will be around for a while.</li> <li>Here's a kicker. I'd like to be able to use advanced presentation layer tools/languages similar to HAML, SASS. I definitively want to use JQuery.</li> <li>I will be creating a Facebook app and at some point doing things like dealing with SMS messages, iPhone apps, etc...</li> </ol> <p>At this point, the choices for language are PHP (Cake,Symfony,Zend), Python (Django), Ruby (Merb). I'm really between Django and Merb at this point mostly because everybody else seems to be going that way. </p> <p>Please don't put any technologies in here that aren't made for mainstream. I know Merb is untested mostly, but their stated goal is a solid platform and it has alot of momentum behind it so I'm confident that it's workable. Please don't answer with how great Perl is or .Net.</p> <p>For Future References - these choices were already made:</p> <ul> <li>Debian (Lenny) - For converting CPU cycles into something useful. Trac</li> <li>0.11 - For Project Management Gliffy - For wireframes and such </li> <li>Google Docs/Apps - For documentation, hosted email, etc... </li> <li>Amazon ec2/S3 - For hosting, storage.</li> </ul> <p>Cheers, Adam </p>
2
2008-10-08T18:07:42Z
186,765
<p>My experience with various new technologies over the last ten years leads me to recommend that you make stability of the platform a serious criterion. It's all well and good developing with the latest and greatest framework, but when you find it's moved forward a point version and suddenly the way you have done everything is deprecated, that can turn out to result in extra unnecessary work. This was particularly my experience working with rails a little ahead of version 1. For that reason alone I would avoid any platform that wasn't at least at 1.0 when you start work on it.</p> <p>Ruby is great to work with and will keep your developer productivity high, but if Django is the more stable platform I would favour that for sure.</p>
0
2008-10-09T11:05:56Z
[ "python", "ruby-on-rails", "django", "merb" ]
Framework/Language for new web 2.0 sites (2008 and 2009)
184,049
<p>I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now:</p> <ol> <li>It is now October 2008. I want to start writing an application for January 2009. I am willing to use beta code and such but by January, I'd like a site that doesn't have 'strange' problems. With that said, if a language is simply 10% slower than another, I don't care about those things as long as the issue is linear. My main concern is developer productivity.</li> <li>I'll be using Linux, Apache, MySQL for the application.</li> <li>I want the power to do things like run scp and ftp client functions with stable libraries (I only picked those two because they're not web-related but at the same time represent pretty common network protocols that any larger app might use). Technologies like OpenID and Oauth will be used as well.</li> <li>Experienced web developers are readily available (i.e. I don't have to find people from financial companies and such).</li> <li>Whatever the choice is is common and will be around for a while.</li> <li>Here's a kicker. I'd like to be able to use advanced presentation layer tools/languages similar to HAML, SASS. I definitively want to use JQuery.</li> <li>I will be creating a Facebook app and at some point doing things like dealing with SMS messages, iPhone apps, etc...</li> </ol> <p>At this point, the choices for language are PHP (Cake,Symfony,Zend), Python (Django), Ruby (Merb). I'm really between Django and Merb at this point mostly because everybody else seems to be going that way. </p> <p>Please don't put any technologies in here that aren't made for mainstream. I know Merb is untested mostly, but their stated goal is a solid platform and it has alot of momentum behind it so I'm confident that it's workable. Please don't answer with how great Perl is or .Net.</p> <p>For Future References - these choices were already made:</p> <ul> <li>Debian (Lenny) - For converting CPU cycles into something useful. Trac</li> <li>0.11 - For Project Management Gliffy - For wireframes and such </li> <li>Google Docs/Apps - For documentation, hosted email, etc... </li> <li>Amazon ec2/S3 - For hosting, storage.</li> </ul> <p>Cheers, Adam </p>
2
2008-10-08T18:07:42Z
188,971
<p>All of them will get the job done.</p> <h2>Use the one that you and your team are most familiar with</h2> <p>This will have a far greater impact on the delivery times and stability of your app than any of the other variables.</p>
7
2008-10-09T20:02:49Z
[ "python", "ruby-on-rails", "django", "merb" ]
Framework/Language for new web 2.0 sites (2008 and 2009)
184,049
<p>I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now:</p> <ol> <li>It is now October 2008. I want to start writing an application for January 2009. I am willing to use beta code and such but by January, I'd like a site that doesn't have 'strange' problems. With that said, if a language is simply 10% slower than another, I don't care about those things as long as the issue is linear. My main concern is developer productivity.</li> <li>I'll be using Linux, Apache, MySQL for the application.</li> <li>I want the power to do things like run scp and ftp client functions with stable libraries (I only picked those two because they're not web-related but at the same time represent pretty common network protocols that any larger app might use). Technologies like OpenID and Oauth will be used as well.</li> <li>Experienced web developers are readily available (i.e. I don't have to find people from financial companies and such).</li> <li>Whatever the choice is is common and will be around for a while.</li> <li>Here's a kicker. I'd like to be able to use advanced presentation layer tools/languages similar to HAML, SASS. I definitively want to use JQuery.</li> <li>I will be creating a Facebook app and at some point doing things like dealing with SMS messages, iPhone apps, etc...</li> </ol> <p>At this point, the choices for language are PHP (Cake,Symfony,Zend), Python (Django), Ruby (Merb). I'm really between Django and Merb at this point mostly because everybody else seems to be going that way. </p> <p>Please don't put any technologies in here that aren't made for mainstream. I know Merb is untested mostly, but their stated goal is a solid platform and it has alot of momentum behind it so I'm confident that it's workable. Please don't answer with how great Perl is or .Net.</p> <p>For Future References - these choices were already made:</p> <ul> <li>Debian (Lenny) - For converting CPU cycles into something useful. Trac</li> <li>0.11 - For Project Management Gliffy - For wireframes and such </li> <li>Google Docs/Apps - For documentation, hosted email, etc... </li> <li>Amazon ec2/S3 - For hosting, storage.</li> </ul> <p>Cheers, Adam </p>
2
2008-10-08T18:07:42Z
189,012
<p>I have to preface this with my agreeing with Orion Edwards, choose the one your team is most familiar with.</p> <p>However, I also have to note the curious lack of ASP.NET languages in your list. Not to provoke the great zealot army, but where's the beef? .NET is a stable, rapid development platform and the labor pool is growing daily. VB.NET and C# are transportable skill sets, and that can mean a lot when you're building a team of developers to work on a diverse set of tasks. .NET also allows you to separate your presentation layer from your backend code, like other languages, but also allows you to expose that backend code as web service for things like your iPhone and Facebook applications.</p> <p>Take every suggestion with a grain of salt, and pick what suits the application best. Do your research, and design for function and not the zealots.</p> <p><em>Disclaimer: Once a PHP, ColdFusion and Perl developer. Flex zealot, and Adobe lover. Now writing enterprise .NET applications. ;)</em></p> <p>Don't forget Mono, which will let you run .NET under *nix. Not that I'm saying it will be perfect, just playing devil's advocate.</p>
1
2008-10-09T20:13:03Z
[ "python", "ruby-on-rails", "django", "merb" ]
Framework/Language for new web 2.0 sites (2008 and 2009)
184,049
<p>I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now:</p> <ol> <li>It is now October 2008. I want to start writing an application for January 2009. I am willing to use beta code and such but by January, I'd like a site that doesn't have 'strange' problems. With that said, if a language is simply 10% slower than another, I don't care about those things as long as the issue is linear. My main concern is developer productivity.</li> <li>I'll be using Linux, Apache, MySQL for the application.</li> <li>I want the power to do things like run scp and ftp client functions with stable libraries (I only picked those two because they're not web-related but at the same time represent pretty common network protocols that any larger app might use). Technologies like OpenID and Oauth will be used as well.</li> <li>Experienced web developers are readily available (i.e. I don't have to find people from financial companies and such).</li> <li>Whatever the choice is is common and will be around for a while.</li> <li>Here's a kicker. I'd like to be able to use advanced presentation layer tools/languages similar to HAML, SASS. I definitively want to use JQuery.</li> <li>I will be creating a Facebook app and at some point doing things like dealing with SMS messages, iPhone apps, etc...</li> </ol> <p>At this point, the choices for language are PHP (Cake,Symfony,Zend), Python (Django), Ruby (Merb). I'm really between Django and Merb at this point mostly because everybody else seems to be going that way. </p> <p>Please don't put any technologies in here that aren't made for mainstream. I know Merb is untested mostly, but their stated goal is a solid platform and it has alot of momentum behind it so I'm confident that it's workable. Please don't answer with how great Perl is or .Net.</p> <p>For Future References - these choices were already made:</p> <ul> <li>Debian (Lenny) - For converting CPU cycles into something useful. Trac</li> <li>0.11 - For Project Management Gliffy - For wireframes and such </li> <li>Google Docs/Apps - For documentation, hosted email, etc... </li> <li>Amazon ec2/S3 - For hosting, storage.</li> </ul> <p>Cheers, Adam </p>
2
2008-10-08T18:07:42Z
189,236
<p>Don't get stuck in the mindset of server-side page layout. Consider technologies like SproutCore, GWT or ExtJS which put the layouting code fully on the client, making the server responsible only for data marshalling and processing (and easily replaced).</p> <p>And you really, really need to know which server platform you want. Don't pick one because it's the flavor of the month, pick one because you're comfortable with it. Flavors don't last, a solidly built codebase will.</p>
1
2008-10-09T21:13:14Z
[ "python", "ruby-on-rails", "django", "merb" ]
Framework/Language for new web 2.0 sites (2008 and 2009)
184,049
<p>I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now:</p> <ol> <li>It is now October 2008. I want to start writing an application for January 2009. I am willing to use beta code and such but by January, I'd like a site that doesn't have 'strange' problems. With that said, if a language is simply 10% slower than another, I don't care about those things as long as the issue is linear. My main concern is developer productivity.</li> <li>I'll be using Linux, Apache, MySQL for the application.</li> <li>I want the power to do things like run scp and ftp client functions with stable libraries (I only picked those two because they're not web-related but at the same time represent pretty common network protocols that any larger app might use). Technologies like OpenID and Oauth will be used as well.</li> <li>Experienced web developers are readily available (i.e. I don't have to find people from financial companies and such).</li> <li>Whatever the choice is is common and will be around for a while.</li> <li>Here's a kicker. I'd like to be able to use advanced presentation layer tools/languages similar to HAML, SASS. I definitively want to use JQuery.</li> <li>I will be creating a Facebook app and at some point doing things like dealing with SMS messages, iPhone apps, etc...</li> </ol> <p>At this point, the choices for language are PHP (Cake,Symfony,Zend), Python (Django), Ruby (Merb). I'm really between Django and Merb at this point mostly because everybody else seems to be going that way. </p> <p>Please don't put any technologies in here that aren't made for mainstream. I know Merb is untested mostly, but their stated goal is a solid platform and it has alot of momentum behind it so I'm confident that it's workable. Please don't answer with how great Perl is or .Net.</p> <p>For Future References - these choices were already made:</p> <ul> <li>Debian (Lenny) - For converting CPU cycles into something useful. Trac</li> <li>0.11 - For Project Management Gliffy - For wireframes and such </li> <li>Google Docs/Apps - For documentation, hosted email, etc... </li> <li>Amazon ec2/S3 - For hosting, storage.</li> </ul> <p>Cheers, Adam </p>
2
2008-10-08T18:07:42Z
201,950
<p>It pays not to be biased about your server setup. Any modern web framework worth it's weight in source code has a SQL abstraction layer of some sort. PostgreSQL gets much better performance, and this is coming from a former MySQL partisan.</p> <p>Apache is a beast, both to configure and on your server's resources. Why not go with something light-weight, like <a href="http://nginx.net" rel="nofollow">nginx</a> or <a href="http://www.lighttpd.net/" rel="nofollow">lighttpd</a>?</p> <p>(For the record, I'm a big Django user, but as the accepted answer said, go with whatever your team knows. Quick turn-arounds are not the time to be learning new frameworks. If you're hiring a team from scratch, go with Django.)</p>
0
2008-10-14T16:48:48Z
[ "python", "ruby-on-rails", "django", "merb" ]
Framework/Language for new web 2.0 sites (2008 and 2009)
184,049
<p>I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now:</p> <ol> <li>It is now October 2008. I want to start writing an application for January 2009. I am willing to use beta code and such but by January, I'd like a site that doesn't have 'strange' problems. With that said, if a language is simply 10% slower than another, I don't care about those things as long as the issue is linear. My main concern is developer productivity.</li> <li>I'll be using Linux, Apache, MySQL for the application.</li> <li>I want the power to do things like run scp and ftp client functions with stable libraries (I only picked those two because they're not web-related but at the same time represent pretty common network protocols that any larger app might use). Technologies like OpenID and Oauth will be used as well.</li> <li>Experienced web developers are readily available (i.e. I don't have to find people from financial companies and such).</li> <li>Whatever the choice is is common and will be around for a while.</li> <li>Here's a kicker. I'd like to be able to use advanced presentation layer tools/languages similar to HAML, SASS. I definitively want to use JQuery.</li> <li>I will be creating a Facebook app and at some point doing things like dealing with SMS messages, iPhone apps, etc...</li> </ol> <p>At this point, the choices for language are PHP (Cake,Symfony,Zend), Python (Django), Ruby (Merb). I'm really between Django and Merb at this point mostly because everybody else seems to be going that way. </p> <p>Please don't put any technologies in here that aren't made for mainstream. I know Merb is untested mostly, but their stated goal is a solid platform and it has alot of momentum behind it so I'm confident that it's workable. Please don't answer with how great Perl is or .Net.</p> <p>For Future References - these choices were already made:</p> <ul> <li>Debian (Lenny) - For converting CPU cycles into something useful. Trac</li> <li>0.11 - For Project Management Gliffy - For wireframes and such </li> <li>Google Docs/Apps - For documentation, hosted email, etc... </li> <li>Amazon ec2/S3 - For hosting, storage.</li> </ul> <p>Cheers, Adam </p>
2
2008-10-08T18:07:42Z
208,938
<p>Having built apps in Django, I can attest to its utility. If only all frameworks were as elegant (yes Spring, I'm looking at you).</p> <p>However in terms of betting the farm on Django, one thing you need to factor in is that Python 3 will be released shortly. Python 3 is not backwards compatible and there's a risk that it will fork the language and end up slowing momentum for all Python projects while they deal with the fallout. To be fair, Ruby 2.0 is due soon too, but I don't think it will be as disruptive. </p>
1
2008-10-16T15:07:01Z
[ "python", "ruby-on-rails", "django", "merb" ]
Framework/Language for new web 2.0 sites (2008 and 2009)
184,049
<p>I know I'll get a thousand "Depends on what you're trying to do" answers, but seriously, there really is no solid information about this online yet. Here are my assumptions - I think they're similar for alot of people right now:</p> <ol> <li>It is now October 2008. I want to start writing an application for January 2009. I am willing to use beta code and such but by January, I'd like a site that doesn't have 'strange' problems. With that said, if a language is simply 10% slower than another, I don't care about those things as long as the issue is linear. My main concern is developer productivity.</li> <li>I'll be using Linux, Apache, MySQL for the application.</li> <li>I want the power to do things like run scp and ftp client functions with stable libraries (I only picked those two because they're not web-related but at the same time represent pretty common network protocols that any larger app might use). Technologies like OpenID and Oauth will be used as well.</li> <li>Experienced web developers are readily available (i.e. I don't have to find people from financial companies and such).</li> <li>Whatever the choice is is common and will be around for a while.</li> <li>Here's a kicker. I'd like to be able to use advanced presentation layer tools/languages similar to HAML, SASS. I definitively want to use JQuery.</li> <li>I will be creating a Facebook app and at some point doing things like dealing with SMS messages, iPhone apps, etc...</li> </ol> <p>At this point, the choices for language are PHP (Cake,Symfony,Zend), Python (Django), Ruby (Merb). I'm really between Django and Merb at this point mostly because everybody else seems to be going that way. </p> <p>Please don't put any technologies in here that aren't made for mainstream. I know Merb is untested mostly, but their stated goal is a solid platform and it has alot of momentum behind it so I'm confident that it's workable. Please don't answer with how great Perl is or .Net.</p> <p>For Future References - these choices were already made:</p> <ul> <li>Debian (Lenny) - For converting CPU cycles into something useful. Trac</li> <li>0.11 - For Project Management Gliffy - For wireframes and such </li> <li>Google Docs/Apps - For documentation, hosted email, etc... </li> <li>Amazon ec2/S3 - For hosting, storage.</li> </ul> <p>Cheers, Adam </p>
2
2008-10-08T18:07:42Z
616,632
<p>Update: I ended up using, and loving, Django. I'm totally done with PHP - sorry about that. Future readers trying to create a new web 2.0 site (assuming they have a programming background), should greatly consider this setup:</p> <p>Amazon ec2 for hosting ($80/month - not cheap but worth it if you can afford it) Django/Python (Python is the most powerful scripting language on the planet - and Django just makes it work on the web)</p> <p>Development should be done with SQLlite and the development server that comes with Django. Don't waste time with Nginx, Apache, MySQL until you're withing a few weeks of a beta.</p> <p>Oh, and I now develop on a Mac, which works great for local Django development.</p> <p>Finally, <a href="http://pinaxproject.com" rel="nofollow">Pinax</a> is a great start for <a href="http://djangoproject.com" rel="nofollow">Django</a> development.</p>
0
2009-03-05T21:09:13Z
[ "python", "ruby-on-rails", "django", "merb" ]
How do I check out a file from perforce in python?
184,187
<p>I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first. </p>
13
2008-10-08T18:33:08Z
184,193
<p>Here's what I came up with:</p> <pre><code>import os def CreateNewChangeList(description): "Create a new changelist and returns the changelist number as a string" p4in, p4out = os.popen2("p4 changelist -i") p4in.write("change: new\n") p4in.write("description: " + description) p4in.close() changelist = p4out.readline().split()[1] return changelist def OpenFileForEdit(file, changelist = ""): "Open a file for edit, if a changelist is passed in then open it in that list" cmd = "p4 edit " if changelist: cmd += " -c " + changelist + " " ret = os.popen(cmd + file).readline().strip() if not ret.endswith("opened for edit"): print "Couldn't open", file, "for edit:" print ret raise ValueError </code></pre>
7
2008-10-08T18:33:51Z
[ "python", "scripting", "perforce" ]
How do I check out a file from perforce in python?
184,187
<p>I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first. </p>
13
2008-10-08T18:33:08Z
184,238
<p>You may want to check out the P4Python module. It's available on the perforce site and it makes things very simple.</p>
2
2008-10-08T18:45:24Z
[ "python", "scripting", "perforce" ]
How do I check out a file from perforce in python?
184,187
<p>I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first. </p>
13
2008-10-08T18:33:08Z
184,344
<p>Perforce has Python wrappers around their C/C++ tools, available in binary form for Windows, and source for other platforms:</p> <p><a href="http://www.perforce.com/perforce/loadsupp.html#api">http://www.perforce.com/perforce/loadsupp.html#api</a></p> <p>You will find their documentation of the scripting API to be helpful:</p> <p><a href="http://www.perforce.com/perforce/doc.current/manuals/p4script/p4script.pdf">http://www.perforce.com/perforce/doc.current/manuals/p4script/p4script.pdf</a></p> <p>Use of the Python API is quite similar to the command-line client:</p> <pre><code>PythonWin 2.5.1 (r251:54863, May 1 2007, 17:47:05) [MSC v.1310 32 bit (Intel)] on win32. Portions Copyright 1994-2006 Mark Hammond - see 'Help/About PythonWin' for further copyright information. &gt;&gt;&gt; import P4 &gt;&gt;&gt; p4 = P4.P4() &gt;&gt;&gt; p4.connect() # connect to the default server, with the default clientspec &gt;&gt;&gt; desc = {"Description": "My new changelist description", ... "Change": "new" ... } &gt;&gt;&gt; p4.input = desc &gt;&gt;&gt; p4.run("changelist", "-i") ['Change 2579505 created.'] &gt;&gt;&gt; </code></pre> <p>I'll verify it from the command line:</p> <pre><code>P:\&gt;p4 changelist -o 2579505 # A Perforce Change Specification. # # Change: The change number. 'new' on a new changelist. # Date: The date this specification was last modified. # Client: The client on which the changelist was created. Read-only. # User: The user who created the changelist. # Status: Either 'pending' or 'submitted'. Read-only. # Description: Comments about the changelist. Required. # Jobs: What opened jobs are to be closed by this changelist. # You may delete jobs from this list. (New changelists only.) # Files: What opened files from the default changelist are to be added # to this changelist. You may delete files from this list. # (New changelists only.) Change: 2579505 Date: 2008/10/08 13:57:02 Client: MYCOMPUTER-DT User: myusername Status: pending Description: My new changelist description </code></pre>
20
2008-10-08T19:02:38Z
[ "python", "scripting", "perforce" ]
How do I check out a file from perforce in python?
184,187
<p>I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first. </p>
13
2008-10-08T18:33:08Z
256,419
<p><a href="http://www.perforce.com/perforce/loadsupp.html#api" rel="nofollow">Perforce's P4 Python module</a> mentioned in another answer is the way to go, but if installing this module isn't an option you can use the -G flag to help parse p4.exe output:</p> <pre><code>p4 [ options ] command [ arg ... ] options: -c client -C charset -d dir -H host -G -L language -p port -P pass -s -Q charset -u user -x file The -G flag causes all output (and batch input for form commands with -i) to be formatted as marshalled Python dictionary objects. </code></pre>
4
2008-11-02T02:28:16Z
[ "python", "scripting", "perforce" ]
How do I check out a file from perforce in python?
184,187
<p>I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first. </p>
13
2008-10-08T18:33:08Z
307,908
<p>Building from p4python source requires downloading and extracting the p4 api recommended for that version. For example, if building the Windows XP x86 version of P4Python 2008.2 for activepython 2.5:</p> <ul> <li>download and extract both the <a href="ftp://ftp.perforce.com/perforce/r08.2/tools/p4python.tgz">p4python</a> and <a href="ftp://ftp.perforce.com/perforce/r08.2/bin.ntx86/p4api_vs2005_static.zip">p4api</a></li> <li>fixup the setup.cfg for p4python to point to the p4api directory.</li> </ul> <p>To open files for edit (do a checkout), on the command line, see 'p4 help open'.</p> <p>You can check out files without making a changelist if you add the file to the default changelist, but it's a good idea to make a changelist first.</p> <p>P4Python doesn't currently compile for activepython 2.6 without visual studio 2008; the provided libs are built with 2005 or 2003. Forcing p4python to build against mingw is nearly impossible, even with pexports of python26.dll and reimp/reassembly of the provided .lib files into .a files.</p> <p>In that case, you'll probably rather use subprocess, and return p4 results as marshalled python objects. You can write your own command wrapper that takes an arg array, constructs and runs the commands, and returns the results dictionary.</p> <p>You might try changing everything, testing, and on success, opening the files that are different with something equivalent to 'p4 diff -se //...'</p>
3
2008-11-21T04:55:35Z
[ "python", "scripting", "perforce" ]
How do I check out a file from perforce in python?
184,187
<p>I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first. </p>
13
2008-10-08T18:33:08Z
4,242,307
<p>Remember guys to install the development package for Python for the p4api or it will complain about missing headers. In Ubuntu 10.10, just do a simple:</p> <pre><code>apt-get install python2.6-dev </code></pre> <p>Or</p> <pre><code>apt-get install python3.1-dev </code></pre>
2
2010-11-22T04:33:38Z
[ "python", "scripting", "perforce" ]
Regular expression to match start of filename and filename extension
185,378
<p>What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'?</p> <p>The regular expression should match any of the following:</p> <pre><code>RunFoo.py RunBar.py Run42.py </code></pre> <p>It should not match:</p> <pre><code>myRunFoo.py RunBar.py1 Run42.txt </code></pre> <p>The SQL equivalent of what I am looking for is <code>... LIKE 'Run%.py' ...</code>.</p>
9
2008-10-08T23:42:27Z
185,387
<p>This probably doesn't fully comply with file-naming standards, but here it goes:</p> <pre><code>/^Run[\w]*?\.py$/ </code></pre>
0
2008-10-08T23:45:57Z
[ "python", "sql", "regex", "like" ]
Regular expression to match start of filename and filename extension
185,378
<p>What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'?</p> <p>The regular expression should match any of the following:</p> <pre><code>RunFoo.py RunBar.py Run42.py </code></pre> <p>It should not match:</p> <pre><code>myRunFoo.py RunBar.py1 Run42.txt </code></pre> <p>The SQL equivalent of what I am looking for is <code>... LIKE 'Run%.py' ...</code>.</p>
9
2008-10-08T23:42:27Z
185,388
<pre><code>/^Run.*\.py$/ </code></pre> <p>Or, in python specifically:</p> <pre><code>import re re.match(r"^Run.*\.py$", stringtocheck) </code></pre> <p>This will match "Runfoobar.py", but not "runfoobar.PY". To make it case insensitive, instead use:</p> <pre><code>re.match(r"^Run.*\.py$", stringtocheck, re.I) </code></pre>
6
2008-10-08T23:46:24Z
[ "python", "sql", "regex", "like" ]
Regular expression to match start of filename and filename extension
185,378
<p>What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'?</p> <p>The regular expression should match any of the following:</p> <pre><code>RunFoo.py RunBar.py Run42.py </code></pre> <p>It should not match:</p> <pre><code>myRunFoo.py RunBar.py1 Run42.txt </code></pre> <p>The SQL equivalent of what I am looking for is <code>... LIKE 'Run%.py' ...</code>.</p>
9
2008-10-08T23:42:27Z
185,393
<p>mabye:</p> <pre><code>^Run.*\.py$ </code></pre> <p>just a quick try</p>
0
2008-10-08T23:47:56Z
[ "python", "sql", "regex", "like" ]
Regular expression to match start of filename and filename extension
185,378
<p>What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'?</p> <p>The regular expression should match any of the following:</p> <pre><code>RunFoo.py RunBar.py Run42.py </code></pre> <p>It should not match:</p> <pre><code>myRunFoo.py RunBar.py1 Run42.txt </code></pre> <p>The SQL equivalent of what I am looking for is <code>... LIKE 'Run%.py' ...</code>.</p>
9
2008-10-08T23:42:27Z
185,397
<p>For a regular expression, you would use:</p> <pre><code>re.match(r'Run.*\.py$') </code></pre> <p>A quick explanation:</p> <ul> <li>. means match any character.</li> <li>* means match any repetition of the previous character (hence .* means any sequence of chars)</li> <li>\ is an escape to escape the explicit dot</li> <li>$ indicates "end of the string", so we don't match "Run_foo.py.txt"</li> </ul> <p>However, for this task, you're probably better off using simple string methods. ie.</p> <pre><code>filename.startswith("Run") and filename.endswith(".py") </code></pre> <p>Note: if you want case insensitivity (ie. matching "run.PY" as well as "Run.py", use the re.I option to the regular expression, or convert to a specific case (eg filename.lower()) before using string methods.</p>
23
2008-10-08T23:48:59Z
[ "python", "sql", "regex", "like" ]
Regular expression to match start of filename and filename extension
185,378
<p>What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'?</p> <p>The regular expression should match any of the following:</p> <pre><code>RunFoo.py RunBar.py Run42.py </code></pre> <p>It should not match:</p> <pre><code>myRunFoo.py RunBar.py1 Run42.txt </code></pre> <p>The SQL equivalent of what I am looking for is <code>... LIKE 'Run%.py' ...</code>.</p>
9
2008-10-08T23:42:27Z
185,426
<p>Warning:</p> <ul> <li>jobscry's answer ("^Run.?.py$") is incorrect (will not match "Run123.py", for example).</li> <li>orlandu63's answer ("/^Run[\w]*?.py$/") will not match "RunFoo.Bar.py".</li> </ul> <p>(I don't have enough reputation to comment, sorry.)</p>
13
2008-10-09T00:01:25Z
[ "python", "sql", "regex", "like" ]
Regular expression to match start of filename and filename extension
185,378
<p>What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'?</p> <p>The regular expression should match any of the following:</p> <pre><code>RunFoo.py RunBar.py Run42.py </code></pre> <p>It should not match:</p> <pre><code>myRunFoo.py RunBar.py1 Run42.txt </code></pre> <p>The SQL equivalent of what I am looking for is <code>... LIKE 'Run%.py' ...</code>.</p>
9
2008-10-08T23:42:27Z
185,583
<p>If you write a slightly more complex regular expression, you can get an extra feature: extract the bit between "Run" and ".py":</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; regex = '^Run(?P&lt;name&gt;.*)\.py$' &gt;&gt;&gt; m = re.match(regex, 'RunFoo.py') &gt;&gt;&gt; m.group('name') 'Foo' </code></pre> <p>(the extra bit is the parentheses and everything between them, except for '.*' which is as in Rob Howard's answer)</p>
2
2008-10-09T01:20:30Z
[ "python", "sql", "regex", "like" ]
Regular expression to match start of filename and filename extension
185,378
<p>What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'?</p> <p>The regular expression should match any of the following:</p> <pre><code>RunFoo.py RunBar.py Run42.py </code></pre> <p>It should not match:</p> <pre><code>myRunFoo.py RunBar.py1 Run42.txt </code></pre> <p>The SQL equivalent of what I am looking for is <code>... LIKE 'Run%.py' ...</code>.</p>
9
2008-10-08T23:42:27Z
185,593
<p>I don't really understand why you're after a regular expression to solve this 'problem'. You're just after a way to find all .py files that start with 'Run'. So this is a simple solution that will work, without resorting to compiling an running a regular expression:</p> <pre><code>import os for filename in os.listdir(dirname): root, ext = os.path.splitext(filename) if root.startswith('Run') and ext == '.py': print filename </code></pre>
11
2008-10-09T01:27:29Z
[ "python", "sql", "regex", "like" ]
Regular expression to match start of filename and filename extension
185,378
<p>What is the regular expression to match strings (in this case, file names) that start with 'Run' and have a filename extension of '.py'?</p> <p>The regular expression should match any of the following:</p> <pre><code>RunFoo.py RunBar.py Run42.py </code></pre> <p>It should not match:</p> <pre><code>myRunFoo.py RunBar.py1 Run42.txt </code></pre> <p>The SQL equivalent of what I am looking for is <code>... LIKE 'Run%.py' ...</code>.</p>
9
2008-10-08T23:42:27Z
186,927
<p>You don't need a regular expression, you can use glob, which takes wildcards e.g. Run*.py</p> <p>For example, to get those files in your current directory...</p> <pre><code>import os, glob files = glob.glob( "".join([ os.getcwd(), "\\Run*.py"]) ) </code></pre>
4
2008-10-09T11:57:56Z
[ "python", "sql", "regex", "like" ]
MVC model structure in Python
185,389
<p>I'm having problems structuring classes in the Model part of an MVC pattern in my Python app. No matter how I turn things, I keep running into circular imports. Here's what I have:</p> <p><strong>Model/__init__p.y</strong></p> <ul> <li>should hold all Model class names so I can do a "from Model import User" e.g. from a Controller or a unit test case</li> </ul> <p><strong>Model/Database.py</strong> </p> <ul> <li>holds Database class</li> <li>needs to import all Model classes to do ORM</li> <li>initialization should be performed on first module import, i.e. no extra init calls or instantiations (all methods on Database class are @classmethods)</li> </ul> <p><strong>Model/User.py</strong></p> <ul> <li>contains User model class</li> <li>needs access to Database class to do queries</li> <li>should inherit from base class common to all Model classes to share functionality (database persistency methods, parameter validation code etc.)</li> </ul> <p>I have yet to see a real world Python app employing MVC, so my approach is probably un-Pythonic (and possibly a language-agnostic mess on top of that...) - any suggestions on how to solve this?</p> <p>Thanks, Simon</p>
2
2008-10-08T23:46:30Z
185,411
<p>Generally, we put it all in one file. This isn't Java or C++.</p> <p>Start with a single file until you get some more experience with Python. Unless your files are gargantuan, it will work fine. </p> <p>For example, Django encourages this style, so copy their formula for success. One module for the model. A module for each application; each application imports a common model.</p> <p>Your Database and superclass stuff can be in your <code>__init__.py</code> file, since it applies to the entire package. That may reduce some of the circularity.</p>
3
2008-10-08T23:55:10Z
[ "python", "model-view-controller", "model", "structure" ]
MVC model structure in Python
185,389
<p>I'm having problems structuring classes in the Model part of an MVC pattern in my Python app. No matter how I turn things, I keep running into circular imports. Here's what I have:</p> <p><strong>Model/__init__p.y</strong></p> <ul> <li>should hold all Model class names so I can do a "from Model import User" e.g. from a Controller or a unit test case</li> </ul> <p><strong>Model/Database.py</strong> </p> <ul> <li>holds Database class</li> <li>needs to import all Model classes to do ORM</li> <li>initialization should be performed on first module import, i.e. no extra init calls or instantiations (all methods on Database class are @classmethods)</li> </ul> <p><strong>Model/User.py</strong></p> <ul> <li>contains User model class</li> <li>needs access to Database class to do queries</li> <li>should inherit from base class common to all Model classes to share functionality (database persistency methods, parameter validation code etc.)</li> </ul> <p>I have yet to see a real world Python app employing MVC, so my approach is probably un-Pythonic (and possibly a language-agnostic mess on top of that...) - any suggestions on how to solve this?</p> <p>Thanks, Simon</p>
2
2008-10-08T23:46:30Z
185,480
<p>I think you have one issue that should be straightened. Circular references often result from a failure to achieve separation of concerns. In my opinion, the database and model modules shouldn't know much about each other, working against an API instead. In this case the database shouldn't directly reference any specific model classes but instead provide the functionality the model classes will need to function. The model in turn, should get a database reference (injected or requested) that it would use to query and persist itself.</p>
1
2008-10-09T00:28:18Z
[ "python", "model-view-controller", "model", "structure" ]
MVC model structure in Python
185,389
<p>I'm having problems structuring classes in the Model part of an MVC pattern in my Python app. No matter how I turn things, I keep running into circular imports. Here's what I have:</p> <p><strong>Model/__init__p.y</strong></p> <ul> <li>should hold all Model class names so I can do a "from Model import User" e.g. from a Controller or a unit test case</li> </ul> <p><strong>Model/Database.py</strong> </p> <ul> <li>holds Database class</li> <li>needs to import all Model classes to do ORM</li> <li>initialization should be performed on first module import, i.e. no extra init calls or instantiations (all methods on Database class are @classmethods)</li> </ul> <p><strong>Model/User.py</strong></p> <ul> <li>contains User model class</li> <li>needs access to Database class to do queries</li> <li>should inherit from base class common to all Model classes to share functionality (database persistency methods, parameter validation code etc.)</li> </ul> <p>I have yet to see a real world Python app employing MVC, so my approach is probably un-Pythonic (and possibly a language-agnostic mess on top of that...) - any suggestions on how to solve this?</p> <p>Thanks, Simon</p>
2
2008-10-08T23:46:30Z
185,692
<p>There is an inconsistency in your specification. You say Database.py needs to import all Model classes to do ORM but then you say the User class need access to the Database to do queries.</p> <p>Think of these as layers of an API. The Database class provides an API (maybe object-oriented) to some physical persistence layer (such as DB-API 2.0). The Model classes, like User, use the Database layer to load and save their state. There is no reason for the Database.py class to import all the Model classes, and in fact you wouldn't want that because you'd have to modify Database.py each time you created a new Model class - which is a code smell.</p>
6
2008-10-09T02:22:03Z
[ "python", "model-view-controller", "model", "structure" ]
Delete Folder Contents in Python
185,936
<p>How can I delete the contents of a local folder in Python?</p> <p>The current project is for Windows but I would like to see *nix also.</p>
171
2008-10-09T04:22:33Z
185,941
<p>Updated to only delete files and to used the os.path.join() method suggested in the comments. If you also want to remove subdirectories, uncomment the elif statement.</p> <pre><code>import os, shutil folder = '/path/to/folder' for the_file in os.listdir(folder): file_path = os.path.join(folder, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) #elif os.path.isdir(file_path): shutil.rmtree(file_path) except Exception as e: print(e) </code></pre>
153
2008-10-09T04:27:21Z
[ "python", "file", "local", "delete-directory" ]
Delete Folder Contents in Python
185,936
<p>How can I delete the contents of a local folder in Python?</p> <p>The current project is for Windows but I would like to see *nix also.</p>
171
2008-10-09T04:22:33Z
186,049
<p>You might be better off using <code>os.walk()</code> for this.</p> <p><code>os.listdir()</code> doesn't distinguish files from directories and you will quickly get into trouble trying to unlink these. There is a good example of using <code>os.walk()</code> to recursively remove a directory <a href="http://docs.python.org/library/os.html#os.walk">here</a>, and hints on how to adapt it to your circumstances.</p>
8
2008-10-09T05:52:54Z
[ "python", "file", "local", "delete-directory" ]
Delete Folder Contents in Python
185,936
<p>How can I delete the contents of a local folder in Python?</p> <p>The current project is for Windows but I would like to see *nix also.</p>
171
2008-10-09T04:22:33Z
186,236
<p>Try the shutil module</p> <pre><code>import shutil shutil.rmtree('/path/to/folder') </code></pre> <blockquote> <p>Description: <code>shutil.rmtree(path, ignore_errors=False, onerror=None)</code></p> <p>Docstring: Recursively delete a directory tree.</p> <p>If <code>ignore_errors</code> is set, errors are ignored; otherwise, if <code>onerror</code> is set, it is called to handle the error with arguments <code>(func, path, exc_info)</code> where <code>func</code> is <code>os.listdir</code>, <code>os.remove</code>, or <code>os.rmdir</code>; path is the argument to that function that caused it to fail; and <code>exc_info</code> is a tuple returned by <code>sys.exc_info()</code>. If <code>ignore_errors</code> is false and <code>onerror</code> is <code>None</code>, an exception is raised.</p> </blockquote>
125
2008-10-09T07:18:35Z
[ "python", "file", "local", "delete-directory" ]
Delete Folder Contents in Python
185,936
<p>How can I delete the contents of a local folder in Python?</p> <p>The current project is for Windows but I would like to see *nix also.</p>
171
2008-10-09T04:22:33Z
1,073,382
<p>Expanding on mhawke's answer this is what I've implemented. It removes all the content of a folder but not the folder itself. Tested on Linux with files, folders and symbolic links, should work on Windows as well.</p> <pre><code>import os import shutil for root, dirs, files in os.walk('/path/to/folder'): for f in files: os.unlink(os.path.join(root, f)) for d in dirs: shutil.rmtree(os.path.join(root, d)) </code></pre>
50
2009-07-02T09:25:56Z
[ "python", "file", "local", "delete-directory" ]
Delete Folder Contents in Python
185,936
<p>How can I delete the contents of a local folder in Python?</p> <p>The current project is for Windows but I would like to see *nix also.</p>
171
2008-10-09T04:22:33Z
5,756,937
<p>You can simply do this :</p> <pre><code>import os import glob files = glob.glob('/YOUR/PATH/*') for f in files: os.remove(f) </code></pre> <p>You can of corse use an other filter in you path, for exemple : /YOU/PATH/*.txt for removing all text files in a directory.</p>
81
2011-04-22T15:23:45Z
[ "python", "file", "local", "delete-directory" ]
Delete Folder Contents in Python
185,936
<p>How can I delete the contents of a local folder in Python?</p> <p>The current project is for Windows but I would like to see *nix also.</p>
171
2008-10-09T04:22:33Z
6,615,332
<p>Using <code>rmtree</code> and recreating the folder could work, but I have run into errors when deleting and immediately recreating folders on network drives.</p> <p>The proposed solution using walk does not work as it uses <code>rmtree</code> to remove folders and then may attempt to use <code>os.unlink</code> on the files that were previously in those folders. This causes an error.</p> <p>The posted <code>glob</code> solution will also attempt to delete non-empty folders, causing errors.</p> <p>I suggest you use:</p> <pre><code>folder_path = '/path/to/folder' for file_object in os.listdir(folder_path): file_object_path = os.path.join(folder_path, file_object) if os.path.isfile(file_object_path): os.unlink(file_object_path) else: shutil.rmtree(file_object_path) </code></pre>
38
2011-07-07T18:25:47Z
[ "python", "file", "local", "delete-directory" ]
Delete Folder Contents in Python
185,936
<p>How can I delete the contents of a local folder in Python?</p> <p>The current project is for Windows but I would like to see *nix also.</p>
171
2008-10-09T04:22:33Z
12,526,809
<p>This is the only answer so far, which:</p> <ul> <li>removes all symbolic links <ul> <li>dead links</li> <li>links to directories</li> <li>links to files</li> </ul></li> <li>removes subdirectories</li> <li>does not remove the parent directory</li> </ul> <p>Code:</p> <pre><code>for filename in os.listdir(dirpath): filepath = os.path.join(dirpath, filename) try: shutil.rmtree(filepath) except OSError: os.remove(filepath) </code></pre> <p>As many other answers, this does not try to adjust permissions to enable removal of files/directories.</p>
4
2012-09-21T08:24:58Z
[ "python", "file", "local", "delete-directory" ]
Delete Folder Contents in Python
185,936
<p>How can I delete the contents of a local folder in Python?</p> <p>The current project is for Windows but I would like to see *nix also.</p>
171
2008-10-09T04:22:33Z
13,666,792
<pre><code>import os import shutil # Gather directory contents contents = [os.path.join(target_dir, i) for i in os.listdir(target_dir)] # Iterate and remove each item in the appropriate manner [shutil.rmtree(i) if os.path.isdir(i) else os.unlink(i) for i in contents] </code></pre>
4
2012-12-02T05:51:33Z
[ "python", "file", "local", "delete-directory" ]
Delete Folder Contents in Python
185,936
<p>How can I delete the contents of a local folder in Python?</p> <p>The current project is for Windows but I would like to see *nix also.</p>
171
2008-10-09T04:22:33Z
16,340,614
<p>I konw it's an old thread but I have found something interesting from the official site of python. Just for sharing another idea for removing of all contents in a directory. Because I have some problems of authorization when using shutil.rmtree() and I don't want to remove the directory and recreate it. The address original is <a href="http://docs.python.org/2/library/os.html#os.walk" rel="nofollow">http://docs.python.org/2/library/os.html#os.walk</a>. Hope that could help someone.</p> <pre><code>def emptydir(top): if(top == '/' or top == "\\"): return else: for root, dirs, files in os.walk(top, topdown=False): for name in files: os.remove(os.path.join(root, name)) for name in dirs: os.rmdir(os.path.join(root, name)) </code></pre>
6
2013-05-02T14:24:00Z
[ "python", "file", "local", "delete-directory" ]
Delete Folder Contents in Python
185,936
<p>How can I delete the contents of a local folder in Python?</p> <p>The current project is for Windows but I would like to see *nix also.</p>
171
2008-10-09T04:22:33Z
17,146,855
<p>I used to solve the problem this way:</p> <pre><code>import shutil import os shutil.rmtree(dirpath) os.mkdir(dirpath) </code></pre>
4
2013-06-17T11:52:24Z
[ "python", "file", "local", "delete-directory" ]
Delete Folder Contents in Python
185,936
<p>How can I delete the contents of a local folder in Python?</p> <p>The current project is for Windows but I would like to see *nix also.</p>
171
2008-10-09T04:22:33Z
20,173,900
<p>As a oneliner:</p> <pre><code>import os # Python 2.7 map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) ) # Python 3+ list( map( os.unlink, (os.path.join( mydir,f) for f in os.listdir(mydir)) ) ) </code></pre>
10
2013-11-24T11:22:15Z
[ "python", "file", "local", "delete-directory" ]
Delete Folder Contents in Python
185,936
<p>How can I delete the contents of a local folder in Python?</p> <p>The current project is for Windows but I would like to see *nix also.</p>
171
2008-10-09T04:22:33Z
23,614,332
<p>Yet Another Solution:</p> <pre><code>import sh sh.rm(sh.glob('/path/to/folder/*')) </code></pre>
5
2014-05-12T16:33:30Z
[ "python", "file", "local", "delete-directory" ]
Delete Folder Contents in Python
185,936
<p>How can I delete the contents of a local folder in Python?</p> <p>The current project is for Windows but I would like to see *nix also.</p>
171
2008-10-09T04:22:33Z
24,844,618
<p><em>Notes: in case someone down voted my answer, I have something to explain here.</em></p> <ol> <li>Everyone likes short 'n' simple answers. However, sometimes the reality is not so simple.</li> <li>Back to my answer. I know <code>shutil.rmtree()</code> could be used to delete a directory tree. I've used it many times in my own projects. But you must realize that <strong>the directory itself will also be deleted by <code>shutil.rmtree()</code></strong>. While this might be acceptable for some, it's not a valid answer for <strong>deleting the contents of a folder (without side effects)</strong>.</li> <li>I'll show you an example of the side effects. Suppose that you have a directory with <strong>customized</strong> owner and mode bits, where there are a lot of contents. Then you delete it with <code>shutil.rmtree()</code> and rebuild it with <code>os.mkdir()</code>. And you'll get an empty directory with <strong>default</strong> (inherited) owner and mode bits instead. While you might have the privilege to delete the contents and even the directory, you might not be able to set back the original owner and mode bits on the directory (e.g. you're not a superuser).</li> <li>Finally, <strong>be patient and read the code</strong>. It's long and ugly (in sight), but proven to be reliable and efficient (in use).</li> </ol> <hr> <p>Here's a long and ugly, but reliable and efficient solution.</p> <p>It resolves a few problems which are not addressed by the other answerers:</p> <ul> <li>It correctly handles symbolic links, including not calling <code>shutil.rmtree()</code> on a symbolic link (which will pass the <code>os.path.isdir()</code> test if it links to a directory; even the result of <code>os.walk()</code> contains symbolic linked directories as well).</li> <li>It handles read-only files nicely.</li> </ul> <p>Here's the code (the only useful function is <code>clear_dir()</code>):</p> <pre><code>import os import stat import shutil # http://stackoverflow.com/questions/1889597/deleting-directory-in-python def _remove_readonly(fn, path_, excinfo): # Handle read-only files and directories if fn is os.rmdir: os.chmod(path_, stat.S_IWRITE) os.rmdir(path_) elif fn is os.remove: os.lchmod(path_, stat.S_IWRITE) os.remove(path_) def force_remove_file_or_symlink(path_): try: os.remove(path_) except OSError: os.lchmod(path_, stat.S_IWRITE) os.remove(path_) # Code from shutil.rmtree() def is_regular_dir(path_): try: mode = os.lstat(path_).st_mode except os.error: mode = 0 return stat.S_ISDIR(mode) def clear_dir(path_): if is_regular_dir(path_): # Given path is a directory, clear its content for name in os.listdir(path_): fullpath = os.path.join(path_, name) if is_regular_dir(fullpath): shutil.rmtree(fullpath, onerror=_remove_readonly) else: force_remove_file_or_symlink(fullpath) else: # Given path is a file or a symlink. # Raise an exception here to avoid accidentally clearing the content # of a symbolic linked directory. raise OSError("Cannot call clear_dir() on a symbolic link") </code></pre>
6
2014-07-19T20:21:55Z
[ "python", "file", "local", "delete-directory" ]
Delete Folder Contents in Python
185,936
<p>How can I delete the contents of a local folder in Python?</p> <p>The current project is for Windows but I would like to see *nix also.</p>
171
2008-10-09T04:22:33Z
37,926,786
<p>This should do the trick just using the OS module to list and then remove!</p> <pre><code>import os DIR = os.list('Folder') for i in range(len(DIR)): os.remove('Folder'+chr(92)+i) </code></pre> <p>Worked for me, any problems let me know! </p>
-1
2016-06-20T15:52:45Z
[ "python", "file", "local", "delete-directory" ]
Extracting unique items from a list of mappings
186,131
<p>He're an interesting problem that looks for the most Pythonic solution. Suppose I have a list of mappings <code>{'id': id, 'url': url}</code>. Some <code>id</code>s in the list are duplicate, and I want to create a new list, with all the duplicates removed. I came up with the following function:</p> <pre><code>def unique_mapping(map): d = {} for res in map: d[res['id']] = res['url'] return [{'id': id, 'url': d[id]} for id in d] </code></pre> <p>I suppose it's quite efficient. But is there a "more Pythonic" way ? Or perhaps a more efficient way ?</p>
2
2008-10-09T06:28:26Z
186,295
<p>Your example can be rewritten slightly to construct the first dictionary using a generator expression and to remove necessity of construction of another mappings. Just reuse the old ones:</p> <pre><code>def unique_mapping(mappings): return dict((m['id'], m) for m in mappings).values() </code></pre> <p>Although this came out as a one-liner, I still think it's quite readable.</p> <p>There are two things you have to keep in mind when using your original solution and mine:</p> <ul> <li>the items will not always be returned in the same order they were originally</li> <li>the later entry will overwrite previous entries with the same id</li> </ul> <p>If you don't mind, then I suggest the solution above. In other case, this function preserves order and treats first-encountered ids with priority:</p> <pre><code>def unique_mapping(mappings): addedIds = set() for m in mappings: mId = m['id'] if mId not in addedIds: addedIds.add(mId) yield m </code></pre> <p>You might need to call it with <code>list(unique_mappings(mappings))</code> if you need a list and not a generator.</p>
4
2008-10-09T07:47:09Z
[ "python", "unique", "duplicate-data" ]
Extracting unique items from a list of mappings
186,131
<p>He're an interesting problem that looks for the most Pythonic solution. Suppose I have a list of mappings <code>{'id': id, 'url': url}</code>. Some <code>id</code>s in the list are duplicate, and I want to create a new list, with all the duplicates removed. I came up with the following function:</p> <pre><code>def unique_mapping(map): d = {} for res in map: d[res['id']] = res['url'] return [{'id': id, 'url': d[id]} for id in d] </code></pre> <p>I suppose it's quite efficient. But is there a "more Pythonic" way ? Or perhaps a more efficient way ?</p>
2
2008-10-09T06:28:26Z
186,317
<p>There are a couple of things you could improve.</p> <ul> <li><p>You're performing two loops, one over the original dict, and then again over the result dict. You could build up your results in one step instead.</p></li> <li><p>You could change to use a generator, to avoid constructing the whole list up-front. (Use list(unique_mapping(items)) to convert to a full list if you need it)</p></li> <li><p>There's no need to store the value when just checking for duplicates, you can use a set instead.</p></li> <li><p>You're recreating a dictionary for each element, rather than returning the original. This may actually be needed (eg. you're modifying them, and don't want to touch the original), but if not, its more efficient to use the dictionaries already created.</p></li> </ul> <p>Here's an implementation:</p> <pre><code>def unique_mapping(items): s = set() for res in items: if res['id'] not in s: yield res s.add(res['id']) </code></pre>
2
2008-10-09T07:54:23Z
[ "python", "unique", "duplicate-data" ]
Extracting unique items from a list of mappings
186,131
<p>He're an interesting problem that looks for the most Pythonic solution. Suppose I have a list of mappings <code>{'id': id, 'url': url}</code>. Some <code>id</code>s in the list are duplicate, and I want to create a new list, with all the duplicates removed. I came up with the following function:</p> <pre><code>def unique_mapping(map): d = {} for res in map: d[res['id']] = res['url'] return [{'id': id, 'url': d[id]} for id in d] </code></pre> <p>I suppose it's quite efficient. But is there a "more Pythonic" way ? Or perhaps a more efficient way ?</p>
2
2008-10-09T06:28:26Z
187,041
<p>I think this can be made simpler still. Dictionaries don't tolerate duplicate keys. Make your list of mappings into a dictionary of mappings. This will remove duplicates.</p> <pre><code>&gt;&gt;&gt; someListOfDicts= [ {'url': 'http://a', 'id': 'a'}, {'url': 'http://b', 'id': 'b'}, {'url': 'http://c', 'id': 'a'}] &gt;&gt;&gt; dict( [(x['id'],x) for x in someListOfDicts ] ).values() [{'url': 'http://c', 'id': 'a'}, {'url': 'http://b', 'id': 'b'}] </code></pre>
1
2008-10-09T12:32:04Z
[ "python", "unique", "duplicate-data" ]
What is the best way to open a file for exclusive access in Python?
186,202
<p>What is the most elegant way to solve this:</p> <ul> <li>open a file for reading, but only if it is not already opened for writing</li> <li>open a file for writing, but only if it is not already opened for reading or writing</li> </ul> <p>The built-in functions work like this</p> <pre><code>&gt;&gt;&gt; path = r"c:\scr.txt" &gt;&gt;&gt; file1 = open(path, "w") &gt;&gt;&gt; print file1 &lt;open file 'c:\scr.txt', mode 'w' at 0x019F88D8&gt; &gt;&gt;&gt; file2 = open(path, "w") &gt;&gt;&gt; print file2 &lt;open file 'c:\scr.txt', mode 'w' at 0x02332188&gt; &gt;&gt;&gt; file1.write("111") &gt;&gt;&gt; file2.write("222") &gt;&gt;&gt; file1.close() </code></pre> <p>scr.txt now contains '111'.</p> <pre><code>&gt;&gt;&gt; file2.close() </code></pre> <p>scr.txt was overwritten and now contains '222' (on Windows, Python 2.4).</p> <p>The solution should work inside the same process (like in the example above) as well as when another process has opened the file.<br /> It is preferred, if a crashing program will not keep the lock open.</p>
29
2008-10-09T06:58:54Z
186,300
<p>To make you safe when opening files within one application, you could try something like this:</p> <pre><code>import time class ExclusiveFile(file): openFiles = {} fileLocks = [] class FileNotExclusiveException(Exception): pass def __init__(self, *args): sMode = 'r' sFileName = args[0] try: sMode = args[1] except: pass while sFileName in ExclusiveFile.fileLocks: time.sleep(1) ExclusiveFile.fileLocks.append(sFileName) if not sFileName in ExclusiveFile.openFiles.keys() or (ExclusiveFile.openFiles[sFileName] == 'r' and sMode == 'r'): ExclusiveFile.openFiles[sFileName] = sMode try: file.__init__(self, sFileName, sMode) finally: ExclusiveFile.fileLocks.remove(sFileName) else: ExclusiveFile.fileLocks.remove(sFileName) raise self.FileNotExclusiveException(sFileName) def close(self): del ExclusiveFile.openFiles[self.name] file.close(self) </code></pre> <p>That way you subclass the <code>file</code> class. Now just do:</p> <pre><code>&gt;&gt;&gt; f = ExclusiveFile('/tmp/a.txt', 'r') &gt;&gt;&gt; f &lt;open file '/tmp/a.txt', mode 'r' at 0xb7d7cc8c&gt; &gt;&gt;&gt; f1 = ExclusiveFile('/tmp/a.txt', 'r') &gt;&gt;&gt; f1 &lt;open file '/tmp/a.txt', mode 'r' at 0xb7d7c814&gt; &gt;&gt;&gt; f2 = ExclusiveFile('/tmp/a.txt', 'w') # can't open it for writing now exclfile.FileNotExclusiveException: /tmp/a.txt </code></pre> <p>If you open it first with 'w' mode, it won't allow anymore opens, even in read mode, just as you wanted...</p>
1
2008-10-09T07:48:44Z
[ "python", "file", "locking" ]
What is the best way to open a file for exclusive access in Python?
186,202
<p>What is the most elegant way to solve this:</p> <ul> <li>open a file for reading, but only if it is not already opened for writing</li> <li>open a file for writing, but only if it is not already opened for reading or writing</li> </ul> <p>The built-in functions work like this</p> <pre><code>&gt;&gt;&gt; path = r"c:\scr.txt" &gt;&gt;&gt; file1 = open(path, "w") &gt;&gt;&gt; print file1 &lt;open file 'c:\scr.txt', mode 'w' at 0x019F88D8&gt; &gt;&gt;&gt; file2 = open(path, "w") &gt;&gt;&gt; print file2 &lt;open file 'c:\scr.txt', mode 'w' at 0x02332188&gt; &gt;&gt;&gt; file1.write("111") &gt;&gt;&gt; file2.write("222") &gt;&gt;&gt; file1.close() </code></pre> <p>scr.txt now contains '111'.</p> <pre><code>&gt;&gt;&gt; file2.close() </code></pre> <p>scr.txt was overwritten and now contains '222' (on Windows, Python 2.4).</p> <p>The solution should work inside the same process (like in the example above) as well as when another process has opened the file.<br /> It is preferred, if a crashing program will not keep the lock open.</p>
29
2008-10-09T06:58:54Z
186,464
<p>I don't think there is a fully crossplatform way. On unix, the fcntl module will do this for you. However on windows (which I assume you are by the paths), you'll need to use the win32file module.</p> <p>Fortunately, there is a portable implementation (<a href="https://github.com/WoLpH/portalocker" rel="nofollow">portalocker</a>) using the platform appropriate method at the python cookbook.</p> <p>To use it, open the file, and then call:</p> <pre><code>portalocker.lock(file, flags) </code></pre> <p>where flags are portalocker.LOCK_EX for exclusive write access, or LOCK_SH for shared, read access.</p>
16
2008-10-09T09:00:09Z
[ "python", "file", "locking" ]
What is the best way to open a file for exclusive access in Python?
186,202
<p>What is the most elegant way to solve this:</p> <ul> <li>open a file for reading, but only if it is not already opened for writing</li> <li>open a file for writing, but only if it is not already opened for reading or writing</li> </ul> <p>The built-in functions work like this</p> <pre><code>&gt;&gt;&gt; path = r"c:\scr.txt" &gt;&gt;&gt; file1 = open(path, "w") &gt;&gt;&gt; print file1 &lt;open file 'c:\scr.txt', mode 'w' at 0x019F88D8&gt; &gt;&gt;&gt; file2 = open(path, "w") &gt;&gt;&gt; print file2 &lt;open file 'c:\scr.txt', mode 'w' at 0x02332188&gt; &gt;&gt;&gt; file1.write("111") &gt;&gt;&gt; file2.write("222") &gt;&gt;&gt; file1.close() </code></pre> <p>scr.txt now contains '111'.</p> <pre><code>&gt;&gt;&gt; file2.close() </code></pre> <p>scr.txt was overwritten and now contains '222' (on Windows, Python 2.4).</p> <p>The solution should work inside the same process (like in the example above) as well as when another process has opened the file.<br /> It is preferred, if a crashing program will not keep the lock open.</p>
29
2008-10-09T06:58:54Z
188,827
<p>Here's a start on the win32 half of a portable implementation, that does not need a seperate locking mechanism.</p> <p>Requires the <a href="http://python.net/crew/mhammond/win32/" rel="nofollow">Python for Windows Extensions</a> to get down to the win32 api, but that's pretty much mandatory for python on windows already, and can alternatively be done with <a href="http://www.python.org/doc/lib/module-ctypes.html" rel="nofollow">ctypes</a>. The code could be adapted to expose more functionality if it's needed (such as allowing <code>FILE_SHARE_READ</code> rather than no sharing at all). See also the MSDN documentation for the <a href="http://msdn.microsoft.com/en-us/library/aa363858.aspx" rel="nofollow"><code>CreateFile</code></a> and <a href="http://msdn.microsoft.com/en-us/library/aa365747.aspx" rel="nofollow"><code>WriteFile</code></a> system calls, and the <a href="http://msdn.microsoft.com/en-us/library/aa363874.aspx" rel="nofollow">article on Creating and Opening Files</a>.</p> <p>As has been mentioned, you can use the standard <a href="http://www.python.org/doc/lib/module-fcntl.html" rel="nofollow">fcntl</a> module to implement the unix half of this, if required.</p> <pre><code>import winerror, pywintypes, win32file class LockError(StandardError): pass class WriteLockedFile(object): """ Using win32 api to achieve something similar to file(path, 'wb') Could be adapted to handle other modes as well. """ def __init__(self, path): try: self._handle = win32file.CreateFile( path, win32file.GENERIC_WRITE, 0, None, win32file.OPEN_ALWAYS, win32file.FILE_ATTRIBUTE_NORMAL, None) except pywintypes.error, e: if e[0] == winerror.ERROR_SHARING_VIOLATION: raise LockError(e[2]) raise def close(self): self._handle.close() def write(self, str): win32file.WriteFile(self._handle, str) </code></pre> <p>Here's how your example from above behaves:</p> <pre><code>&gt;&gt;&gt; path = "C:\\scr.txt" &gt;&gt;&gt; file1 = WriteLockedFile(path) &gt;&gt;&gt; file2 = WriteLockedFile(path) #doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... LockError: ... &gt;&gt;&gt; file1.write("111") &gt;&gt;&gt; file1.close() &gt;&gt;&gt; print file(path).read() 111 </code></pre>
2
2008-10-09T19:30:33Z
[ "python", "file", "locking" ]
What is the best way to open a file for exclusive access in Python?
186,202
<p>What is the most elegant way to solve this:</p> <ul> <li>open a file for reading, but only if it is not already opened for writing</li> <li>open a file for writing, but only if it is not already opened for reading or writing</li> </ul> <p>The built-in functions work like this</p> <pre><code>&gt;&gt;&gt; path = r"c:\scr.txt" &gt;&gt;&gt; file1 = open(path, "w") &gt;&gt;&gt; print file1 &lt;open file 'c:\scr.txt', mode 'w' at 0x019F88D8&gt; &gt;&gt;&gt; file2 = open(path, "w") &gt;&gt;&gt; print file2 &lt;open file 'c:\scr.txt', mode 'w' at 0x02332188&gt; &gt;&gt;&gt; file1.write("111") &gt;&gt;&gt; file2.write("222") &gt;&gt;&gt; file1.close() </code></pre> <p>scr.txt now contains '111'.</p> <pre><code>&gt;&gt;&gt; file2.close() </code></pre> <p>scr.txt was overwritten and now contains '222' (on Windows, Python 2.4).</p> <p>The solution should work inside the same process (like in the example above) as well as when another process has opened the file.<br /> It is preferred, if a crashing program will not keep the lock open.</p>
29
2008-10-09T06:58:54Z
195,021
<blockquote> <p>The solution should work inside the same process (like in the example above) as well as when another process has opened the file.</p> </blockquote> <p>If by 'another process' you mean 'whatever process' (i.e. not your program), in Linux there's no way to accomplish this relying only on system calls (<em>fcntl</em> &amp; friends). What you want is <a href="http://en.wikipedia.org/wiki/File_locking">mandatory locking</a>, and the Linux way to obtain it is a bit more involved:</p> <p>Remount the partition that contains your file with the <em>mand</em> option:</p> <pre><code># mount -o remount,mand /dev/hdXY</code></pre> <p>Set the <em>sgid</em> flag for your file:</p> <pre><code># chmod g-x,g+s yourfile</code></pre> <p>In your Python code, obtain an exclusive lock on that file:</p> <pre><code>fcntl.flock(fd, fcntl.LOCK_EX)</code></pre> <p>Now even <em>cat</em> will not be able to read the file until you release the lock. </p>
6
2008-10-12T02:46:56Z
[ "python", "file", "locking" ]
What is the best way to open a file for exclusive access in Python?
186,202
<p>What is the most elegant way to solve this:</p> <ul> <li>open a file for reading, but only if it is not already opened for writing</li> <li>open a file for writing, but only if it is not already opened for reading or writing</li> </ul> <p>The built-in functions work like this</p> <pre><code>&gt;&gt;&gt; path = r"c:\scr.txt" &gt;&gt;&gt; file1 = open(path, "w") &gt;&gt;&gt; print file1 &lt;open file 'c:\scr.txt', mode 'w' at 0x019F88D8&gt; &gt;&gt;&gt; file2 = open(path, "w") &gt;&gt;&gt; print file2 &lt;open file 'c:\scr.txt', mode 'w' at 0x02332188&gt; &gt;&gt;&gt; file1.write("111") &gt;&gt;&gt; file2.write("222") &gt;&gt;&gt; file1.close() </code></pre> <p>scr.txt now contains '111'.</p> <pre><code>&gt;&gt;&gt; file2.close() </code></pre> <p>scr.txt was overwritten and now contains '222' (on Windows, Python 2.4).</p> <p>The solution should work inside the same process (like in the example above) as well as when another process has opened the file.<br /> It is preferred, if a crashing program will not keep the lock open.</p>
29
2008-10-09T06:58:54Z
21,444,311
<p>Assuming your Python interpreter, and the underlying os and filesystem treat os.rename as an atomic operation and it will error when the destination exists, the following method is free of race conditions. I'm using this in production on a linux machine. Requires no third party libs and is not os dependent, and aside from an extra file create, the performance hit is acceptable for many use cases. You can easily apply python's function decorator pattern or a 'with_statement' contextmanager here to abstract out the mess.</p> <p>You'll need to make sure that lock_filename does not exist before a new process/task begins.</p> <pre><code>import os,time def get_tmp_file(): filename='tmp_%s_%s'%(os.getpid(),time.time()) open(filename).close() return filename def do_exclusive_work(): print 'exclusive work being done...' num_tries=10 wait_time=10 lock_filename='filename.lock' acquired=False for try_num in xrange(num_tries): tmp_filename=get_tmp_file() if not os.path.exists(lock_filename): try: os.rename(tmp_filename,lock_filename) acquired=True except (OSError,ValueError,IOError), e: pass if acquired: try: do_exclusive_work() finally: os.remove(lock_filename) break os.remove(tmp_filename) time.sleep(wait_time) assert acquired, 'maximum tries reached, failed to acquire lock file' </code></pre> <p><strong>EDIT</strong></p> <p>It has come to light that os.rename silently overwrites the destination on a non-windows OS. Thanks for pointing this out @ akrueger!</p> <p>Here is a workaround, gathered from <a href="http://stackoverflow.com/questions/1348026/how-do-i-create-a-file-in-python-without-overwriting-an-existing-file">here</a>:</p> <p>Instead of using os.rename you can use:</p> <pre><code>try: if os.name != 'nt': # non-windows needs a create-exclusive operation fd = os.open(lock_filename, os.O_WRONLY | os.O_CREAT | os.O_EXCL) os.close(fd) # non-windows os.rename will overwrite lock_filename silently. # We leave this call in here just so the tmp file is deleted but it could be refactored so the tmp file is never even generated for a non-windows OS os.rename(tmp_filename,lock_filename) acquired=True except (OSError,ValueError,IOError), e: if os.name != 'nt' and not 'File exists' in str(e): raise </code></pre> <p>@ akrueger You're probably just fine with your directory based solution, just giving you an alternate method.</p>
1
2014-01-29T22:45:22Z
[ "python", "file", "locking" ]
What is the best way to open a file for exclusive access in Python?
186,202
<p>What is the most elegant way to solve this:</p> <ul> <li>open a file for reading, but only if it is not already opened for writing</li> <li>open a file for writing, but only if it is not already opened for reading or writing</li> </ul> <p>The built-in functions work like this</p> <pre><code>&gt;&gt;&gt; path = r"c:\scr.txt" &gt;&gt;&gt; file1 = open(path, "w") &gt;&gt;&gt; print file1 &lt;open file 'c:\scr.txt', mode 'w' at 0x019F88D8&gt; &gt;&gt;&gt; file2 = open(path, "w") &gt;&gt;&gt; print file2 &lt;open file 'c:\scr.txt', mode 'w' at 0x02332188&gt; &gt;&gt;&gt; file1.write("111") &gt;&gt;&gt; file2.write("222") &gt;&gt;&gt; file1.close() </code></pre> <p>scr.txt now contains '111'.</p> <pre><code>&gt;&gt;&gt; file2.close() </code></pre> <p>scr.txt was overwritten and now contains '222' (on Windows, Python 2.4).</p> <p>The solution should work inside the same process (like in the example above) as well as when another process has opened the file.<br /> It is preferred, if a crashing program will not keep the lock open.</p>
29
2008-10-09T06:58:54Z
28,532,580
<p>EDIT: <strong>I solved it myself!</strong> By using <strong><em>directory existence</em></strong> &amp; age as a locking mechanism! Locking by file is safe only on Windows (because Linux silently overwrites), but locking by directory works perfectly both on Linux and Windows. See my GIT where I created an easy to use class <strong>'lockbydir.DLock'</strong> for that:</p> <p><a href="https://github.com/drandreaskrueger/lockbydir" rel="nofollow">https://github.com/drandreaskrueger/lockbydir</a></p> <p>At the bottom of the readme, you find 3 GITplayers where you can see the code examples execute live in your browser! Quite cool, isn't it? :-)</p> <p>Thanks for your attention</p> <hr> <h2>This was my original question:</h2> <p>I would like to answer to parity3 (<a href="http://meta.stackoverflow.com/users/1454536/parity3">http://meta.stackoverflow.com/users/1454536/parity3</a>) but I can neither comment directly ('You must have 50 reputation to comment'), nor do I see any way to contact him/her directly. What do you suggest to me, to get through to him?</p> <p>My question:</p> <p>I have implemented something similiar to what parity3 suggested here as an answer: <a href="http://stackoverflow.com/a/21444311/3693375">http://stackoverflow.com/a/21444311/3693375</a> ("Assuming your Python interpreter, and the ...")</p> <p>And it works brilliantly - on Windows. (I am using it to implement a locking mechanism that works across independently started processes. <a href="https://github.com/drandreaskrueger/lockbyfile" rel="nofollow">https://github.com/drandreaskrueger/lockbyfile</a> )</p> <p>But other than parity3 says, it does NOT work the same on Linux:</p> <blockquote> <p>os.rename(src, dst)</p> <p>Rename the file or directory src to dst. ... On Unix, if dst exists and is a file, it will be replaced silently if the user has permission. The operation may fail on some Unix flavors if src and dst are on different filesystems. If successful, the renaming will be an atomic operation (this is a POSIX requirement). On Windows, if dst already exists, OSError will be raised (<a href="https://docs.python.org/2/library/os.html#os.rename" rel="nofollow">https://docs.python.org/2/library/os.html#os.rename</a>)</p> </blockquote> <p>The silent replacing is the problem. On Linux. The "if dst already exists, OSError will be raised" is great for my purposes. But only on Windows, sadly.</p> <p>I guess parity3's example still works most of the time, because of his if condition</p> <pre><code>if not os.path.exists(lock_filename): try: os.rename(tmp_filename,lock_filename) </code></pre> <p>But then the whole thing is not atomic anymore. </p> <p>Because the if condition might be true in two parallel processes, and then both will rename, but only one will win the renaming race. And no exception raised (in Linux).</p> <p>Any suggestions? Thanks! </p> <p>P.S.: I know this is not the proper way, but I am lacking an alternative. PLEASE don't punish me with lowering my reputation. I looked around a lot, to solve this myself. How to PM users in here? And <em>meh</em> why can't I?</p>
2
2015-02-15T23:41:16Z
[ "python", "file", "locking" ]
Python - How to use Conch to create a Virtual SSH server
186,316
<p>I'm looking at creating a server in python that I can run, and will work as an SSH server. This will then let different users login, and act as if they'd logged in normally, but only had access to one command.</p> <p>I want to do this so that I can have a system where I can add users to without having to create a system wide account, so that they can then, for example, commit to a VCS branch, or similar.</p> <p>While I can work out how to do this with conch to get it to a "custom" shell... I can't figure out how to make it so that the SSH stream works as if it were a real one (I'm preferably wanting to limit to /bin/bzr so that bzr+ssh will work.</p> <p>It needs to be in python (which i can get to do the authorisation) but don't know how to do the linking to the app. </p> <p>This needs to be in python to work within the app its designed for, and to be able to be used for those without access to add new users</p>
5
2008-10-09T07:54:12Z
186,465
<p>While Python really is my favorite language, I think you need not create you own server for this. When you look at the <a href="http://www.openbsd.org/cgi-bin/man.cgi?query=sshd&amp;sektion=8" rel="nofollow">OpenSSH Manualpage for sshd</a> you'll find the "command" options for the authorized keys file that lets you define a specific command to run on login.</p> <p>Using keys, you can use one system account to allow many user to log in, just put their public keys in the account's authorized keys file.</p> <p>We are using this to create SSH tunnels for SVN and it works just great.</p>
-2
2008-10-09T09:00:11Z
[ "python", "twisted" ]
Python - How to use Conch to create a Virtual SSH server
186,316
<p>I'm looking at creating a server in python that I can run, and will work as an SSH server. This will then let different users login, and act as if they'd logged in normally, but only had access to one command.</p> <p>I want to do this so that I can have a system where I can add users to without having to create a system wide account, so that they can then, for example, commit to a VCS branch, or similar.</p> <p>While I can work out how to do this with conch to get it to a "custom" shell... I can't figure out how to make it so that the SSH stream works as if it were a real one (I'm preferably wanting to limit to /bin/bzr so that bzr+ssh will work.</p> <p>It needs to be in python (which i can get to do the authorisation) but don't know how to do the linking to the app. </p> <p>This needs to be in python to work within the app its designed for, and to be able to be used for those without access to add new users</p>
5
2008-10-09T07:54:12Z
189,452
<p>When you write a Conch server, you can control what happens when the client makes a shell request by implementing <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/conch/interfaces.py?rev=24441#L62"><code>ISession.openShell</code></a>. The Conch server will request <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/conch/interfaces.py?rev=24441#L6"><code>IConchUser</code></a> from your realm and then adapt the resulting avatar to <code>ISession</code> to call <code>openShell</code> on it if necessary.</p> <p><code>ISession.openShell</code>'s job is to take the transport object passed to it and associate it with a protocol to interpret the bytes received from it and, if desired, to write bytes to it to be sent to the client.</p> <p>In an unfortunate twist, the object passed to <code>openShell</code> which represents the transport is actually an <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/internet/interfaces.py?rev=24441#L1028"><code>IProcessProtocol</code></a> provider. This means that you need to call <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/internet/interfaces.py?rev=24441#L1033"><code>makeConnection</code></a> on it, passing an <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/internet/interfaces.py?rev=24441#L1261"><code>IProcessTransport</code></a> provider. When data is received from the client, the <code>IProcessProtocol</code> will call <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/internet/interfaces.py?rev=24441#L1282"><code>writeToChild</code></a> on the transport you pass to <code>makeConnection</code>. When you want to send data to the client, you should call <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/internet/interfaces.py?rev=24441#L1043"><code>childDataReceived</code></a> on it.</p> <p>To see the exact behavior, I suggest reading <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/conch/ssh/session.py?rev=24441#L173">the implementation of the <code>IProcessProtocol</code> that is passed in</a>. Don't depend on anything that's not part of <code>IProcessProtocol</code>, but seeing the implementation can make it easier to understand what's going on.</p> <p>You may also want to look at <a href="http://twistedmatrix.com/trac/browser/trunk/twisted/conch/unix.py?rev=24441#L174">the implementation of the normal shell-creation</a> to get a sense of what you're aiming for. This will give you a clue about how to associate the stdio of the bzr child process you launch with the SSH channel.</p>
7
2008-10-09T22:30:29Z
[ "python", "twisted" ]
'from X import a' versus 'import X; X.a'
186,472
<p>I've seen some Python programmers use the following style fairly consistently (we'll call it style 1):</p> <pre><code>import some_module # Use some_module.some_identifier in various places. </code></pre> <p>For support of this style, you can cite the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"explicit is better than implicit"</a> maxim. I've seen other programmers use this style (style 2):</p> <pre><code>from some_module import some_identifier # Use some_identifier in various places. </code></pre> <p>The primary benefit that I see in style 2 is maintainability -- especially with <a href="http://en.wikipedia.org/wiki/Duck_typing" rel="nofollow">duck typing</a> ideals I may want to swap some_module for some_other_module. I also feel style 2 wins points with the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"readability counts"</a> maxim. Although I tend to disagree, one can always argue that search-and-replace is just as good an option when using the first style.</p> <p><strong>Addendum:</strong> It was noted that you could use <code>as</code> to solve the switch from <code>some_module</code> to <code>some_other_module</code> in style 1. I forgot to mention that it is also common to decide to implement <code>some_identifier</code> in your <em>current</em> module, which makes creation of an equivalent <code>some_module</code> container slightly awkward.</p>
7
2008-10-09T09:04:34Z
186,483
<p>With the existence of the following syntax:</p> <pre><code>import some_other_module as some_module </code></pre> <p>the maintainability argument of style 2 is no longer relevant.</p> <p>I tend to use style 1. Normally, I find that I explicitly reference the imported package name only a few times in a typical Python program. Everything else is methods on the object, which of course don't need to reference the imported package.</p>
5
2008-10-09T09:08:22Z
[ "python", "python-import", "maintainability", "duck-typing" ]
'from X import a' versus 'import X; X.a'
186,472
<p>I've seen some Python programmers use the following style fairly consistently (we'll call it style 1):</p> <pre><code>import some_module # Use some_module.some_identifier in various places. </code></pre> <p>For support of this style, you can cite the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"explicit is better than implicit"</a> maxim. I've seen other programmers use this style (style 2):</p> <pre><code>from some_module import some_identifier # Use some_identifier in various places. </code></pre> <p>The primary benefit that I see in style 2 is maintainability -- especially with <a href="http://en.wikipedia.org/wiki/Duck_typing" rel="nofollow">duck typing</a> ideals I may want to swap some_module for some_other_module. I also feel style 2 wins points with the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"readability counts"</a> maxim. Although I tend to disagree, one can always argue that search-and-replace is just as good an option when using the first style.</p> <p><strong>Addendum:</strong> It was noted that you could use <code>as</code> to solve the switch from <code>some_module</code> to <code>some_other_module</code> in style 1. I forgot to mention that it is also common to decide to implement <code>some_identifier</code> in your <em>current</em> module, which makes creation of an equivalent <code>some_module</code> container slightly awkward.</p>
7
2008-10-09T09:04:34Z
186,485
<p>I usually use a threshold to decide this. If I want to use a lot of things within <code>some_module</code>, I'll use:</p> <pre><code>import some_module as sm x = sm.whatever </code></pre> <p>If there's only one or two things I need:</p> <pre><code>from some_module import whatever x = whatever </code></pre> <p>That's assuming I don't need a <code>whatever</code> from <code>some_other_module</code>, of course.</p> <p>I tend to use the <code>as</code> clause on the imports so that I can reduce my typing <strong>and</strong> substitue another module quite easily in the future.</p>
2
2008-10-09T09:09:49Z
[ "python", "python-import", "maintainability", "duck-typing" ]
'from X import a' versus 'import X; X.a'
186,472
<p>I've seen some Python programmers use the following style fairly consistently (we'll call it style 1):</p> <pre><code>import some_module # Use some_module.some_identifier in various places. </code></pre> <p>For support of this style, you can cite the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"explicit is better than implicit"</a> maxim. I've seen other programmers use this style (style 2):</p> <pre><code>from some_module import some_identifier # Use some_identifier in various places. </code></pre> <p>The primary benefit that I see in style 2 is maintainability -- especially with <a href="http://en.wikipedia.org/wiki/Duck_typing" rel="nofollow">duck typing</a> ideals I may want to swap some_module for some_other_module. I also feel style 2 wins points with the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">"readability counts"</a> maxim. Although I tend to disagree, one can always argue that search-and-replace is just as good an option when using the first style.</p> <p><strong>Addendum:</strong> It was noted that you could use <code>as</code> to solve the switch from <code>some_module</code> to <code>some_other_module</code> in style 1. I forgot to mention that it is also common to decide to implement <code>some_identifier</code> in your <em>current</em> module, which makes creation of an equivalent <code>some_module</code> container slightly awkward.</p>
7
2008-10-09T09:04:34Z
186,486
<p>I believe in newer versions of Python (2.5+? must check my facts...) you can even do:</p> <pre><code>import some_other_module as some_module </code></pre> <p>So you could still go with style 1 and swap in a different module later on.</p> <p>I think it generally maps to how much you want to clutter up your namespace. Will you just be using one or two names in the module? Or all of them (<code>from x import *</code> is not allways bad, just generally)?</p>
0
2008-10-09T09:10:18Z
[ "python", "python-import", "maintainability", "duck-typing" ]