Add line numbers to your source code with expand and some quick perl:
expand /etc/motd | perl -pe 's/^/\t=$.=\t/'
commandsexpandlanguagesperlprogramming
Add the following code to the top of a CGI Python script to enable colorized, annotated traceback formatting whenever a fatal error occurs in your script:
import cgitb; cgitb.enable()
When in development mode, this is likely more helpful than a '500 Internal Server Error'.
cgicolorerrorsfatalimportlanguagesmodulesprogrammingpythonscripttraceback
Use the pycolor tool included with ipython. It will format the source using ASCII codes so it looks pretty in your terminal:
$ pycolor foo.py
asciicommandsipythonlanguagesprogrammingpycolorpythonterminal
os.mkdir raises a generic exception if an error occurs, but typically you need to ignore preexisting directory errors. Here's how to ignore them:
import os, errno, sys
myPath = "/path/to/dir"
try:
os.mkdir(myPath)
except Exception, e:
code, st = e
if code != errno.EEXIST:
st = "Error creating directory '%s': %s" % (myPath, str(e))
sys.exit(1)
directoryexceptionslanguagesmkdirosprogrammingpython
An essential part of any CGI written in perl that will push all the fatal errors to the browser instead of punting with the all-too-familiar 500 Internal Server error:
use CGI::Carp qw(fatalsToBrowser);
carpcgilanguagesmodulesperlprogramming
Type perldoc -f <function_name> for syntax help. Also, perldoc -q <regexp> will search question headings in the perlfaq[1-9] man pages.
commandsdocslanguagesmanpagesperlperldocprogramming
An often-used concept in shell scripting is globbing. You can use this in python, as well:
import glob
for textFile in glob.glob("*.txt"):
# Do something with 'textFile'.
globimportlanguagesmodulesprogrammingpythonshell
Use the psycopg.Binary() function to escape the binary data:
>>> db = psycopg.connect("dbname=%s user=%s" % (database, user))
>>> db.autocommit(True)
>>> cursor = db.cursor()
>>> file = "/path/to/binary_file.jpg"
>>> fd = open(file, "r")
>>> contents = fd.read(os.stat(file)[6])
>>> fd.close()
>>> cursor.execute("INSERT INTO pr0n (image) VALUES (%s)", (psycopg.Binary(contents)))
binarybyteacursordbapiescapeinteractivelanguagespostgresqlprogrammingpsycopgpython
If you're using os.system to run a command (such as xterm running man) and you get "broken pipe" errors, you can restore standard pipe functionality with the signal module:
import signal signal.signal(signal.SIGPIPE, signal.SIG_DFL) # Call os.system after calling signal.signal.
Note: information taken from http://monkeyfingers.org/ (page now unavailable).
brokenlanguagesospipeprogrammingpythonsignalsystemunix
Here's how to declare parameter arrays in C++/CLI:
int Add(... List<int>^ numbers)
{
int total = 0;
for each(int i in numbers)
{
total += i;
}
return total;
}
cppcppclidotnetlanguagesprogramming
To make print suppress its usual trailing newline, add a comma to the end of the statement:
print "Foo", print "Foo %s" % (bar),
languagesprintprogrammingpythonsyntaxtrailing-newline
If you're using the psycopg Python module to connect to Postgres, you may find that you have old scripts that use version 1 of psycopg but you have version 2 installed and don't want to modify your scripts. At the time of this writing (and according to http://initd.org/tracker/psycopg/wiki/Migration), the version 2 module provides a very easy "compatibility mode". Just import the psycopg1 submodule and alias it, or fall back to the version 1 module if version 2 is not available:
try:
# Try importing the compatibility submodule, which will only
# work if psycopg version 2 is available.
import psycopg.psycopg1 as psycopg
except Exception, e:
# Fall back to version 1.
import psycopg
aliasdbapiimportlanguagespostgresqlprogrammingpsycopgpsycopg2python
If you need your script to have access to ActiveRecord, ActiveMail, et al. you can place these directives at the top of your script:
#!/usr/bin/env ruby require 'rubygems' require_gem 'activesupport'
activerecordconfigurationlanguagesmodulesprogrammingrailsrorruby
Sometimes it's necessary to access raw post data. The easiest way to do this is by opening the php://input stream:
$fp = fopen('php://input', 'r');
httpiolanguagesphppostprogrammingsyntax
Remove duplicate elements from a list:
newList = dict([(item, 1) for item in oldList]).keys()
Or, if you have Python 2.3 or newer, you can use a Set object to collapse your list:
import sets newList = list(sets.Set(oldList))
dataimportlanguagesprogrammingpythonsetsyntax
If you're having to match lines that start with # you can avoid using an expression if you do something like this:
foreach ($lines as $line) {
if ($line{0} != '#') {
// We have a non-comment, print it.
echo $line . '<br />';
}
}
foreachlanguagesphpprogrammingsyntax
Given an array @slobber, replace all the CR-LF with CR:
foreach (@slobber) {
s/\015\012$/\n/; print;
}
dosforeachlanguagesline-endingsperlprogrammingsyntaxunix
Beware that on some versions of PHP, the PHP session ID value is a hexadecimal hash but on some newer systems the configuration is used to adjust the contents of the session ID string:
; Define how many bits are stored in each character when converting ; the binary hash data to something readable. ; ; 4 bits: 0-9, a-f ; 5 bits: 0-9, a-v ; 6 bits: 0-9, a-z, A-Z, "-", "," session.hash_bits_per_character = 5
configurationgotchahexadecimallanguagesphpphp.iniprogrammingsession
Use this elisp snippet (in your ~/.emacs) to instruct your Emacs python-mode to use the proper python executable on a system with multiple pythons installed:
(setq py-python-command "/usr/bin/python2.3")
dotemacselispemacsinterpreterinvocationlanguagesprogrammingpython
You can specify the search path(s) used by ld at runtime to find shared objects by building your program with the -rpath option:
$ gcc -Xlinker -rpath -Xlinker /path/to/my/libraries filename.c
This is the equivalent of:
$ ld -rpath /path/to/my/libraries filename.o
ccommandscompilationgcclanguagesldlinkingprogramming
You can use PHP's trim function to remove non-printable characters:
$string = trim($string, "\x7f..\xff\x0..\x1f");
charactersfunctionslanguagesnon-printablephpprogrammingtrim
If you want to list the symbols of your object code, you can use the nm command:
$ nm object_file.o
ccommandslanguagesnmprogramming
When using sessions in PHP, the default PHP configuration causes PHP to send a no-cache header to your browser so that session-managed pages are not cached. Sometimes this is not the desired behavior, such as when writing a script whose output is binary data such as images which are stored in a database. If this is the case, you can turn off the caching by using functions to modify the PHP configuration on a per-request basis. Call these functions before calling the session_start() function:
// Let the browser and proxies cache output
session_cache_limiter('public');
// One-day (60 * 24, in minutes) cache expiration time for output
session_cache_expire(60 * 24);
(Note: this behavior is documented at http://www.php.net/manual/en/ref.session.php.)
functionsheadershttplanguagesphpprogrammingsession
If you need a function to build a big block of text and return it at the end, you may be concatenating all of the pieces of text into one big string. Rather, you can use a generator to return the text cleanly and efficiently:
def buildText():
yield "This is the first line."
for i in range(10):
yield "Line %d" % (i)
yield "This is the last line."
Then, you can automatically build a list of the generator's results:
results = list(buildText())
(To learn more about generators, see "the python tutorial" at http://docs.python.org/tut/node11.html#SECTION00111000000000000000000.)
efficiencygeneratorslanguagesprogrammingpython