Monthly Archives: July 2015

Xenophon’s Anabasis

The Anabasis is Xenophon’s best known work. Besides being the first known work of what later became as popular literary type–the account of a military expedition cast int he form of a novel–it is often studied by beginning students of Ancient Greek because of Xenophon’s simple and direct, yet vivid, prose. He was the Hemingway of Attic Greek.

The name “Anabasis” means “Going Up” but came to connote a march or military expedition “up country”. After Xenophon numerous Anabasi were written in imitation, The most famous is the Anabasis of Alexander by Arrian of Nicomedia. The title of Xenophon’s Anabasis plays a role in a humorous sketch provided by John Henry Newman, in his The Idea of a University, in which a young student, seeking admission to a university, has asked to be examined on the works of Xenophon,

Tutor. Mr. Brown, I believe? sit down.

Candidate. Yes.

T. What are the Latin and Greek books you propose to be examined in?

C. Homer, Lucian, Demosthenes, Xenophon, Virgil, Horace, Statius, Juvenal, Cicero, Analecta, and Matthiæ.

T. No; I mean what are the books I am to examine you in?

C. is silent.

T. The two books, one Latin and one Greek: don’t flurry yourself.

C. Oh, … Xenophon and Virgil.

T. Xenophon and Virgil. Very well; what part of Xenophon?

C. is silent.

T. What work of Xenophon?

C. Xenophon.

T. Xenophon wrote many works. Do you know the names of any of them?

C. I … Xenophon … Xenophon.

T. Is it the Anabasis you take up?

C. (with surprise) O yes; the Anabasis.

T. Well, Xenophon’s Anabasis; now what is the meaning of the word anabasis?

C. is silent.

T. You know very well; take your time, and don’t be alarmed. Anabasis means …

C. An ascent.

T. Very right; it means an ascent. Now how comes it to mean an ascent? What is it derived from?

C. It comes from … (a pause). Anabasis … it is the nominative.

T. Quite right: but what part of speech is it?

C. A noun,—a noun substantive.

T. Very well; a noun substantive, now what is the verb that anabasis is derived from?

C. is silent.

T. From the verb ἀναβαίνω, isn’t it? from ἀναβαίνω.

C. Yes.

T. Just so. Now, what does ἀναβαίνω mean?

C. To go up, to ascend.

T. Very well; and which part of the word means to go, and which part up?

C. ἀνά is up, and βαίνω go.

T. βαίνω to go, yes; now, βάσις? What does βάσις mean?

C. A going.

T. That is right; and ἀνά-βασις?

C. A going up.

T. Well, now you say Anabasis means an ascent. Who ascended?

C. The Greeks, Xenophon.

T. Very well: Xenophon and the Greeks; the Greeks ascended. To what did they ascend?

C. Against the Persian king: they ascended to fight the Persian king.

T. That is right … an ascent; but I thought we called it a descent when a foreign army carried war into a country?

C. is silent.

Etc.

It is hard to imagine that anyone reading the Anabasis would not know what it was about, since it is a very engaging book in any language. An army of around 10,000 Greek mercenaries, recruited from throughout the Hellenic world are hired by Cyrus the younger, a Persian prince, ostensibly for use in a local brush war. Soon after the men are gathered, however, it becomes clear that Cyrus actually intends to use the army to attack his older brother and place himself on the throne. With some misgivings the 10,000 agree to follow Cyrus. Unfortunately in the first real battle, a nominal victory for Cyrus’ army, Cyrus himself is killed. After multiple disastrous attempts to parlay with the Great King the mercenaries realize that he absolutely can’t be trusted. Accordingly, they set off to march and fight their way across the breath of the Persian Empire and Armenia to reach the Black Sea where Greek cities offer the chance of taking ship for home.

Illustrations of Greek Soldiers from An Illustrated Dictionary to Xenophon's Anabasis, 1892 [public domain via Internet Archive]

Illustrations of Greek Soldiers from An Illustrated Dictionary to Xenophon’s Anabasis, 1892 [public domain via Internet Archive]

The Anabasis more or less introduces the literary trope of the “wandering mercenary company”, which has since been used by numerous authors. It is easy to draw parallels with the free company in Arthur Conan Doyle’s The White Company, for instance. The trope is a mainstay of military sci-fi: David Drake’s Hammer’s Slammers was one of the most successful series of the 1980’s. A somewhat more recent example is David Weber’s and John Ringo’s March Upcountry tetralogy, the name of which is itself a nod to the Anabasis. In fantasy the exploits of the mercenary companies in Glen Cook’s long running Black Company series and Barbara Hambly’s Sun Wolf and Starhawk trilogy are utterly unforgettable. More recently, “sell sword” companies play a recurring role in George R. R. Martin’s Song of Ice and Fire series Of course, there have been plenty of historical mercenary units since the time of Xenophon. Yet his way of writing about life in a mercenary army seems to have set the pattern for all later authors.

One of the interesting things that differentiates Xenophon’s 10,000 from many other armies, particularly the Persian forces that they fought, is that it never has unity of command. There are rarely less than five generals in command at any given time. Towards the end of the book Xenophon himself, who has accepted a generalship to replace a man killed by Persian treachery, is increasingly able to dominate the other four. He is never able to ignore their wishes completely, though. When he tries to simply override them they take their own men and do what they want. Still less are the generals able to ignore the will of the common soldiers. The generals command in the heat of battle but all other decisions are put to a vote. And if a general becomes too unpopular he faces a real chance of getting lynched by his own men.

Another interesting feature of Xenophon’s account is that he is the first military author I am aware of who actually mentions camp followers. In most armies in history the number of actual armed “effectives” was dwarfed by the hostlers, merchants, mistresses, prostitutes, servants, and others who traveled with them. In the ancient world, when slaves were an important type of individual wealth, a successful army was usually further swelled by numerous captives bound for sale in the first slave market the army came to. This is why it is interesting that historians like Thucydides and Herodotus never mention any of these people. In Xenophon, however, the need to protect the camp followers is mentioned as a recurring tactical consideration. While he doesn’t attempt to count them, it is clear that they are numerous and are regarded as bona fide stakeholders in the overall venture.

It is also interesting that Xenophon mentions the presence of “comrade-women”,

As soon as the victims were favourable, all the soldiers began singing the battle hymn, and with the notes of the paean mingled the shouting of the men accompanied by the shriller chant of the women, for there were many comrade-women in the camp.

It is hard to say whether these women were primarily prostitutes, mistresses, or adventurers in their own right. They certainly weren’t wives–he mentions several times how eager the men were to return to their families back in Hellas. It certainly seems though, that while they could not have been expected to have fought in the hopelite battle line, these “comrade-women” were present and played a role in battle. This is yet another of the tantalizing mentions of women that we find in various works that is so at odds with the accepted view of women in the Greek world as a secluded and disenpowered class that was rarely allowed out of the women’s part of the house.

Overall, Xenophon was an important literary innovator whose books are still accessible and interesting to the modern reader. While they do not always make their way onto the various published Great Books lists, I still would recommend them. And if you only read one of his books, the Anabasis is probably the one you should pick.

Note: The Penguin Group’s popular translation of the Anabasis is sold as The Persian Expedition. I personally read Dakyns’ translation, which is also quite good and is available from Project Gutenberg.

Advertisements

Dynamic HTML in Python – A Simple E-Book Server

I thought it was high time I wrote another Python how-to article, since I haven’t for months, and they tend to be the highest traffic posts on this site. This one should give you plenty of “bang for your buck”, though, since it includes examples of web development, file i/o, and working with PDF files.

I should start with a little background to the problem. I have an older Kindle device, to which I am more or less addicted. I download hundreds of classic books, technical manuals, and journal articles, put them on the Kindle, and read them at my leisure. Unfortunately, the device only has 2 gigabytes of storage. This seems like a lot, but by the time I downloaded all the books on my Great Books Reading List on it, it was already 3/4 full. Lately I’ve been having to delete files to make room for new ones–which is a problem, because I don’t always know where to find them again if I need them. A few weeks ago I complained about the problem on Facebook, and one of my buddies suggested (jokingly?) that I build a “Kindle Server”. So I did.

It only took a couple of hours to dump all of my books on one of the servers that live in my garage, set up a simple Python-based web server, and write a Python script to dynamically serve up a listing of titles. Now I just point my Kindle’s browser at the server and download whatever I want on the fly.

This works with non-DRM .MOBI files, like the ones on Project Gutenberg, The Online Library of Liberty, and the University of Adelaide. It also works on .PDF files. It ignores DRP protected Kindle books that you bought from Amazon, because they stay in the “Archived Items” folder on your Kindle and you can re-download them directly from Amazon.

Step 1 – Set Up a Web Server

Python itself comes with all the libraries you need to function as a simple CGI web sever. A simple script like this, slightly adapted from an example on the Pointless Programming blog, should be all you need. Note that my web server root directory is “/var/www”, my Kindle books are in “/var/www/kindle” and my CGI scripts are in “/var/www/cgi-bin”. I don’t have another server on that IP, so I could use port 80, which is the “main” web server port.

#!/usr/bin/env python

import BaseHTTPServer
import CGIHTTPServer
import cgitb; cgitb.enable()  

server = BaseHTTPServer.HTTPServer
handler = CGIHTTPServer.CGIHTTPRequestHandler
server_address = ("", 80)
handler.cgi_directories = ["/cgi-bin"]

httpd = server(server_address, handler)
httpd.serve_forever()

Once you make sure the web server is working correctly, you will probably want to add a few lines to your rc.local file to start it in the background on system startup:

cd /var/www
./webserver.py &

Step 2 – Write the CGI Script

This is a mildly long script, so I will break it down and explain it by sections. The entire source file is at the bottom of this post.

The first lines in the script tell the server to use Python to run is and import the libraries that you will need. “os” is used to read the directory and is included with Python. “pyPdf” is used to get titles from PDF files and is widely available in repositories. On Debian based systems the package is called “python-pypdf”.

#! /usr/bin/env python

import os
from pyPdf import PdfFileReader

Here we print some text to let browser know that it is receiving HTML output. We also set the title of the page and print a header at the top.

print "Content-Type: text/html"
print
print """
<html>
<head><title>Kindle Library</title></head>
<body>
<h1>Kindle Library</h1><hr>
<ul>
"""

Here we initialize blank lists: one for MOBI format books, one for PDF format books, and one for subdirectories.

mobifiles = []
pdffiles = []
dirlist = []

Now we get a listing of the directory where the books are stored and sort the entries based on the file extension. Anything without an extension is assumed to be a subdirectory and anything with an unrecognized extension is simply ignored.

filelist = os.listdir("/var/www/kindle")
for f in filelist:
    if os.path.splitext(f)[1] == ".mobi":
        mobifiles.append("/var/www/kindle/"+f)
    elif os.path.splitext(f)[1] == ".pdf":
        pdffiles.append("/var/www/kindle/"+f)
    elif os.path.splitext(f)[1] == "":
        dirlist.append("/var/www/kindle/"+f)

And now we do the same thing for any files in subdirectories.

for d in dirlist:
    filelist = os.listdir(d)
    for f in filelist:
        if os.path.splitext(f)[1] == ".mobi":
            mobifiles.append(d+'/'+f)
        elif os.path.splitext(f)[1] == ".pdf":
            pdffiles.append("/var/www/kindle/"+f)

This code looks in each of the MOBI format files and extracts a title. The MOBI format is a fairly complex binary file–usually compressed–and I couldn’t easily find a Python library to read the metadata. Let me know if you know of one. A little tinkering with a hex dumper revealed that the first 32 bytes of each file contain an abbreviated title, which works fine for this application.

Screen Shot of Hex Dump

Screen Shot of Hex Dump

print "<h2>Kindle MOBI Books</h2>"
booklinks = []
for f in mobifiles:
    with open(f, "rb") as book:
        t = book.read(32)
        title = t.strip()
        title = title.replace("_", " ")
    booklinks.append(['<li><a href="'+f.replace("/var/www/","/")+'">',
          title,"</a></li>"])

And then this part sorts the list by title and prints the hyperlinked titles.

booklinks.sort(key=lambda x: x[1])      #sort by title

for b in booklinks:
    print b[0]+b[1]+b[2]

print "</ul>"

This part does the same thing for .PDF books. The PyPdf library makes it silly easy to retrieve PDF metadata. The only thing to worry about is that not all PDF creators bother to put a title in. When the title returns as “None” we use the file name for a title.

print "<h2>PDF Books</h2>"
print "<ul>" 
booklinks = [] 
for f in pdffiles: 
    pdfinput = PdfFileReader(file(f, "rb")) 
    title = str(pdfinput.getDocumentInfo().title) 
    if title == "None": 
        title = f.replace("/var/www/kindle/", "") 
    booklinks.append(['<li><a href="'+f.replace("/var/www/",
                "/")+'">',title,"</a></li>"]) 

booklinks.sort(key=lambda x: x[1]) #sort by title 

for b in booklinks: 
    print b[0]+b[1]+b[2] 
    print "</ul>"</ul>

And, finally, we print a count of the number of books and subdirectories and close the <body> and <html> tags.

print str(len(mobifiles)+len(pdffiles)), "books in", 
print str(len(dirlist)+1), "directories.
"

print """
</body>
</html>
"""

Remember to move the finished script to your /cgi-bin directory and change the permissions to make it executable for all users.

The final result runs fast and looks pretty slick:

Screen Shot from Browser

Screen Shot from Browser

It would be easy to add some CSS to make it even prettier, but I didn’t bother since I’ll mostly be looking at it though a Kindle screen:

Screen Shot from Kindle

Screen Shot from Kindle

I hope this is helpful to you. If nothing else, it shows good simple examples of how to create dynamic HTML with Python and how to get the titles from MOBI and PDF files.

Full Source Listing

#! /usr/bin/env python

import os
from pyPdf import PdfFileReader

print "Content-Type: text/html"
print
print """
<html>
<head><title>Kindle Library</title></head>
<body>
<h1>Kindle Library</h1><hr>
<ul>
"""

mobifiles = []
pdffiles = []
dirlist = []

filelist = os.listdir("/var/www/kindle")
for f in filelist:
    if os.path.splitext(f)[1] == ".mobi":
        mobifiles.append("/var/www/kindle/"+f)
    elif os.path.splitext(f)[1] == ".pdf":
        pdffiles.append("/var/www/kindle/"+f)
    elif os.path.splitext(f)[1] == "":
        dirlist.append("/var/www/kindle/"+f)

for d in dirlist:
    filelist = os.listdir(d)
    for f in filelist:
        if os.path.splitext(f)[1] == ".mobi":
            mobifiles.append(d+'/'+f)   
        elif os.path.splitext(f)[1] == ".pdf":
            pdffiles.append("/var/www/kindle/"+f)

print "<h2>Kindle MOBI Books</h2>"
booklinks = []
for f in mobifiles:
    with open(f, "rb") as book:
        t = book.read(32)
        title = t.strip()
        title = title.replace("_", " ")
    booklinks.append(['<li><a href="'+f.replace("/var/www/",
            "/")+'">',title,"</a></li>"])
    
booklinks.sort(key=lambda x: x[1])      #sort by title

for b in booklinks:
    print b[0]+b[1]+b[2]
        
print "</ul>"

print "<h2>PDF Books</h2>"
print "<ul>"

booklinks = []
for f in pdffiles:
    pdfinput = PdfFileReader(file(f, "rb"))
    title = str(pdfinput.getDocumentInfo().title)
    if title == "None":
        title = f.replace("/var/www/kindle/", "")
    booklinks.append(['<li><a href="'+f.replace("/var/www/",
            "/")+'">',title,"</a></li>"])
    
booklinks.sort(key=lambda x: x[1])      #sort by title   

for b in booklinks:
    print b[0]+b[1]+b[2]

print "</ul>"
    
print str(len(mobifiles)+len(pdffiles)), "books in", 
print str(len(dirlist)+1), "directories.<br>"



print """
</body>
</html>
"""

Apology of Xenophon

Apology of Xenophon

Since in the last post I wrote about Plato’s Apology, it seems timely to consider Xenophon’s Apology, which was probably written around the same time or shortly later. Xenophon, like Plato, had studied under Socrates as a young man. unlike Plato, it is impossible that he could actually have attended Socrates’ trial because we know he was fighting in a Persian civil war in 399 (the story of which is told in his book The Anabasis). His information comes second hand, though a friend named Hermogenes, son of Hipponicus.

Xenophon [public domain via Wikimedia]

Xenophon [public domain via Wikimedia]

Xenophon’s apology is considerably shorter than Plato’s. By his own admission, he makes no attempt to dwell on philosophy but merely strives to explain Socrates’ attitude towards death. In a way this is a back-handed critique of Plato and other philosophers who, in their accounts of Socrates, tended to put words into the master’s mouth to legitimize their own philosophic theories. Actually, however, Xenophon’s Apology is just as much a testament to the writer’s personal philosophy as any of the others. The difference is that Xenophon, while he was prolific writer, was never a professional philosopher like Plato. He was, above all else, a mercenary soldier and his Socrates demonstrates a simple soldier’s philosophy: Don’t fear death, because it’s better do die quickly and escape the depredations of old age. Live as well as you can, but don’t apologize to anyone.

Xenophon’s Socrates makes no effort to craft an artful speech in his defense, even when urged by his friends, saying that his life so far is all the defense he needs,

Do you not know that up to this moment I will not concede to any man to have lived a better life than I have; since what can exceed the pleasure, which has been mine, of knowing 10 that my whole life has been spent holily and justly? And indeed this verdict of self-approval I found re-echoed in the opinion which my friends and intimates have formed concerning me. 11 And now if my age is still to be prolonged, 12 I know that I cannot escape paying 13 the penalty of old age, in increasing dimness of sight and dulness of hearing. I shall find myself slower to learn new lessons, and apter to forget the lessons I have learnt. And if to these be added the consciousness of failing powers, the sting of self-reproach, what prospect have I of any further joy in living?

The Athenian juries disagrees when the time comes, but this is of no great import to Socrates, who answers to no one but his daemon and himself. He takes the poison with good grace, embracing the painless death at the the height of his intellectual prime which, to him, is so preferable to future senility or present exile.

Apology of Plato

Two posts ago I wrote about the difficulty we encounter, when reading Plato’s dialogs, distinguishing his teachings from those of Socrates. Because the Apology is an early dialog and the subject matter is Socrates himself, it may give the most accurate portrait of him of all the dialogs. The apology is a “transcript” of Socrates’ defense while on trial for his life. In the decade following his execution (in 399 BCE) a number of authors wrote their own accounts of the trial, and Plato probably wanted to create a definitive version to defend the memory of his teacher. Of course no record of the trial is completely accurate, if only because the Greeks had not yet invented the concept of a court reporter and thus had to rely on their memories of what was said.

Socrates Dictates his Will, Josef Abel, 1800 [public domain via Rijksmuseum]

Socrates Dictates his Will, Josef Abel, 1800 [public domain via Rijksmuseum]

One of the most important things to remember when reading the Apology, is that Socrates really didn’t care whether he won or lost the trial. He was 70 years old and had already reached a place in his philosophy in which he no longer feared death,

For let me tell you, gentlemen, that to be afraid of death is only another form of thinking that one is wise when one is not; it is to think that one knows when one does not know. No one knows with regard to death whether it is not really the greatest blessing that can happen to a man; but people dread it as though they are certain that it is the greatest evil; and this ignorance, which thinks that it knows what it does not, must surely be ignorance most culpable. (29a-b)

Transcending fear, particularly the fear of death, is one of the great benefits of studying philosophy. Unmotivated by fear, Socrates was free to follow his own convictions–and possibly the urgings of his daemon–and seize on the trial as one more chance to educate the Athenians and set an example for his students by demonstrating his dialectic.

Thus Socrates, whose disclaimer that he doesn’t know how to speak in court sounds weak from a man who has already put the greatest sophists of the day in their place, spends most of the trial bringing up edgy theological ideas, such as when he calls on the god Apollo as a witness or when, in passing, he asserts that the Gods cannot lie. Both of these points required a number of unorthodox assumptions and would have made most of the jurors uncomfortable. Socrates then goes on to demonstrate his teaching method by cross examining Meletus which, to most of the jurors, would have been more a demonstration of how annoying he could be. Towards the end of his defense he declines to beg for the court’s mercy (a standard section in Athenian court practice) and explains away his lack of political service by saying that he just would have been gotten himself killed by the other Athenians had he involved himself,

The true champion of justice, if he intends to survive even a short time, must necessarily confine himself to private life and leave politics alone. (32a)

No one, least of all Socrates, is surprised when the court returns a “guilty” verdict. The prosecution recommends the death penalty. Athenian law allows the defendant to propose his own penalty, and everyone expects him to suggest exile, which the jury will probably accept. Instead, he proposes a trivially small fine, saying its the most he can afford. He then raises the number, after Crito and others offer to pay. Obviously, though, if Socrates’ friends are paying it won’t really be a punishment.

Socrates is sentenced to die and soon becomes the most famous martyr to philosophy in Western history (or perhaps the second most famous, depending how one classifies Jesus).

Socrates and Plato [public domain via Internet Archive]

Socrates and Plato [public domain via Internet Archive]

At this point, let’s pause to contrast the careers of Socrates and Plato. Socrates “The Gadfly” was an outsider who was always as odds with, and ultimately executed by, the system. Plato was a respected citizen who died in his sleep at a party. Socrates’ teachings were primarily dialectical–dealing with ways to change and improve society. Plato’s were primarily metaphysical and idealistic and implied that one might as well accept society because the physical world wasn’t the real world anyway as well as advocating a world view that was ultimately static. Socrates discarded his (probably lower-middle) social class and became something else. Plato remained close to his aristocratic roots. Socrates conversed in the streets and at dinner parties. Plato taught at an a academy.

If we think of “philosopher” as a role in society then, in many ways, these two men are the original archetypes of the two kinds of philosopher that have historically been found in Western Civilization. For want of better terminology, I call them Outsiders and Academics, and I am currently writing a book about the Outsiders. While I would of course love it if you were to buy my book, when it comes out, everything you really need to know about the two can be found by studying Socrates and Plato. Outsiders like Socrates are the initiators: they force society to examine new ideas. Since societies don’t really like new ideas, the Outsiders usually suffer for it, financially and/or physically. The Academics, on the other hand, safe within legitimized social organizations such as universities, are the developers and guardians of the new ideas which were first introduced by outsiders. Occasionally, an academic is able to conceive and promulgate a truly original idea, but this is rare because the process they go through to earn their positions selects against innovators and because they have too much to loose to buck the system. Our civilization seems to need both types of philosopher to function.