C
HAPTER
-1. W
HAT
S
N
EW
I
N
“D
IVE
I
NTO
P
YTHON
3”
Isn’t this wherewecamein?
—PinkFloyd,TheWall
-1.1.
A
.
K
.
A
.“
THE MINUSLEVEL
Y
oureadthe original “
Dive Into Python” andmaybe evenboughtitonpaper.(Thanks!)Youalready
know Python2prettywell. You’re readyto take the plunge into Python3.…If allofthat is true,readon.
(Ifnone ofthatistrue, you’dbe betteroff
starting at the beginning.)
Python3comeswitha scriptcalled
2to3
.Learnit. Love it. Use it.
Porting Code toPython3with
2to3
isa
referenceofallthe thingsthat the
2to3
tool canfixautomatically.Since a lotofthosethingsare syntax
changes, it’s agoodstartingpointtolearnabout a lotofthesyntaxchangesinPython3. (
print
isnow a
function,
`x`
doesn’twork,
&
c.)
Case Study:Porting
chardet
to Python3documentsmy(ultimately successful)effort to porta non-trivial
library fromPython2 to Python3. Itmayhelpyou; itmaynot. There’sa fairlysteeplearning curve, since
youneedto kindofunderstand the libraryfirst, so youcanunderstandwhyitbrokeandhow Ifixedit. A
lot ofthe breakagecenters aroundstrings. Speaking ofwhich…
Strings. Whew.Where to start. Python2had“strings” and“Unicodestrings.” Python3 has “bytes” and
“strings.” Thatis, allstringsare nowUnicode strings, and ifyouwant to dealwitha bag ofbytes, you use
the new
bytes
type. Python3will never implicitlyconvertbetweenstringsandbytes, so ifyou’re notsure
whichone youhave atanygivenmoment,yourcode willalmostcertainlybreak. Read
the Stringschapter
formoredetails.
Bytesvs. stringscomesupagainandagainthroughoutthe book.
1
Pdf protected mode - C# PDF Password Library: add, remove, edit PDF file password in C#.net, ASP.NET, MVC, WinForms, WPF
Help to Improve the Security of Your PDF Document by Setting Password
create password protected pdf online; create copy protected pdf
Pdf protected mode - VB.NET PDF Password Library: add, remove, edit PDF file password in vb.net, ASP.NET, MVC, WinForms, WPF
Help to Improve the Security of Your PDF Document by Setting Password
pdf password recovery; pdf password
• In
Files, you’lllearnthe difference betweenreading filesin“binary” and“text” mode.Reading (andwriting!)
filesintext mode requires an
encoding
parameter. Some text filemethodscountcharacters, butother
methods count bytes.Ifyour codeassumes thatone character==onebyte, itwillbreakonmulti-byte
characters.
• In
HTTP
WebServices,the
httplib2
module fetches headersanddata over
HTTP
.
HTTP
headersare
returned as strings,but the
HTTP
bodyisreturnedasbytes.
• In
Serializing PythonObjects, you’ll learnwhythe
pickle
moduleinPython3defines a new data format that
isbackwardly incompatible with Python2.(Hint: it’sbecause ofbytes and strings.) Also
JSON
,whichdoesn’t
support the
bytes
typeat all.I’ll showyouhowto hack aroundthat.
• In
Case study:porting
chardet
to Python3, it’sjusta bloodymessofbytesandstringseverywhere.
Evenifyoudon’tcare aboutUnicode(oh butyouwill), you’ll want to readabout
string formattinginPython
3, whichiscompletelydifferentfromPython2.
Iteratorsare everywhere inPython 3,andIunderstandthema lot betterthanIdidfiveyears ago whenI
wrote “Dive Into Python”. Youneedto understand themtoo, because lotsoffunctionsthatusedto return
lists inPython2will nowreturniteratorsinPython3. At a minimum,youshouldread
the second halfof
the Iteratorschapterand
the secondhalfoftheAdvancedIterators chapter.
Bypopular request,I’ve added anappendixon
SpecialMethodNames, whichis kindoflike
thePythondocs
“Data Model” chapter butwithmore snark.
WhenIwaswriting “Dive Into Python”, all ofthe available XML librariessucked.ThenFredrik Lundhwrote
ElementTree,whichdoesn’tsuck atall. The Pythongodswisely
incorporated ElementTreeinto thestandard
library,andnowitformsthe basisfor
mynew XML chapter. Theoldwaysofparsing XML are still around,
butyoushouldavoidthem,because theysuck!
Also newinPython—notinthe language butinthecommunity—istheemergence of coderepositories
like
The PythonPackage Index(PyPI).Pythoncomes withutilities to package your code instandardformats
anddistribute those packagesonPyPI. Read
Packaging PythonLibrariesfor details.
2
C#: How to Add HTML5 Document Viewer Control to Your Web Page
userDefined", FileName: "/RasterEdge_Demo_Docs/pdf/demo_1.pdf" })); _tabDemoFiles. addCommand AppSettings.Get("resourceFolder"); protected void Page_Load(object
adding a password to a pdf; add password to pdf file without acrobat
C# Image: How to Integrate Web Document and Image Viewer
RasterEdgeImagingDeveloperGuide8.0.pdf: from this user manual, you can find the detailed public string mode; public string fid; protected void Page_Load
copy protected pdf to word converter online; break password pdf
C
HAPTER
0. I
NSTALLING
P
YTHON
Tempora mutanturnos et mutamurin illis.(Timeschange,and wechangewith them.)
—ancient Romanproverb
0.1. D
IVING
I
N
W
elcometo Python3. Let's dive in.Inthischapter, you'll install the versionofPython3 that'sright
foryou.
0.2.W
HICH
P
YTHON
I
S
R
IGHT
F
OR
Y
OU
?
Thefirst thingyouneedto do withPythonis installit. Ordoyou?
Ifyou're usinganaccountona hostedserver, your
ISP
mayhavealreadyinstalled Python3.Ifyou’re running
Linuxat home, youmayalreadyhave Python3, too.Mostpopular GNU/Linuxdistributionscome with
Python2inthe default installation; asmall butgrowing numberofdistributionsalso includePython3.Mac
OS Xincludesa command-line versionofPython2, butasofthiswriting it does not include Python3.
Microsoft WindowsdoesnotcomewithanyversionofPython. Butdon’tdespair!Youcanpoint-and-click
yourwaythroughinstalling Python, regardless ofwhatoperating systemyouhave.
Theeasiest wayto check forPython3onyourLinuxorMacOSXsystemisto get to a commandline. On
Linux, look inyour
Applications
menufor a programcalled
Terminal
.(It maybe ina submenulike
Accessories
or
System
.) OnMacOS X, there isanapplicationcalled
Terminal.app
inyour
/Application/
Utilities/
folder.
Once you’reata commandline prompt, justtype
python3
(all lowercase, nospaces)andsee what happens.
OnmyhomeLinuxsystem, Python3isalready installed, andthiscommandgetsmeinto the Python
interactiveshell.
3
C# TIFF: C#.NET Code to Create Online TIFF Document Viewer
We still demonstrate how to create more web viewers on PDF and Word documents at the public string mode; public string fid; protected void Page_Load
pdf document password; create password protected pdf
C# Word: How to Create Word Online Viewer in C# Application
For PDF and TIFF web viewer creating, you can go to PDF Web Viewer Creation in C#.NET and public string mode; public string fid; protected void Page_Load
advanced pdf password remover; password on pdf file
mark@atlantis:~$ python3
Python 3.0.1+ (r301:69556, Apr 15 2009, 17:25:52)
[GCC 4.3.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
(Type
exit()
and press
ENTER
to exitthePythoninteractive shell.)
My
webhostingprovideralso runsLinuxand providescommand-line access,but myserverdoesnothave
Python3installed. (Boo!)
mark@manganese:~$ python3
bash: python3: command not found
So back to the question thatstartedthissection, “WhichPythonisrightforyou?” Whicheverone runson
the computer youalreadyhave.
[Read onfor Windows instructions,or skipto
Installing onMacOS X,
Installing onUbuntuLinux, or
Installing onOtherPlatforms.]
0.3.I
NSTALLINGON
M
ICROSOFT
W
INDOWS
Windowscomesintwo architecturesthesedays: 32-bitand64-bit. Ofcourse,therearelotsofdifferent
versions ofWindows—XP, Vista, Windows 7—butPythonrunsonall ofthem.The more important
distinctionis32-bitv. 64-bit.Ifyouhave no idea what architecture you’re running,it’sprobably32-bit.
Visit
python.org/download/
anddownload the appropriatePython3Windowsinstaller for yourarchitecture.
Your choiceswilllook something like this:
• Python3.1 Windows installer(Windowsbinary—does not include source)
4
C# DICOM - How to Create Web Viewer
Allow C#.NET users to save or print (convert) web DICOM file to TIFF or PDF file. public string mode; public string fid; protected void Page_Load(object
acrobat password protect pdf; pdf owner password
C# Excel: Tutorial for Web Excel Document Viewer Creation
Support saving modified Excel document PDF and TIFF files within C#.NET web program. public string mode; public string fid; protected void Page_Load
pdf protected mode; convert password protected pdf to normal pdf online
• Python3.1 Windows AMD64 installer(WindowsAMD64 binary—doesnotinclude source)
Idon’twant to include direct download linkshere, because minorupdatesofPython happenall the time and
Idon’twant to be responsiblefor youmissing important updates.Youshouldalwaysinstallthemostrecent
version ofPython3.xunlessyouhavesomeesotericreasonnotto.
Once yourdownloadis complete, double-
click the
.msi
file.Windowswillpopupa
securityalert,since you’re aboutto be
running executablecode. The officialPython
installer is digitallysignedbythe
Python
Software Foundation,thenon-profit
corporationthatoverseesPython
development. Don’tacceptimitations!
Click the
Run
buttonto launchthePython3
installer.
5
C# PowerPoint: Create Web Document Viewer for PowerPoint Viewing
Support converting and saving web PowerPoint document to PDF and TIFF. Here we provide public string mode; public string fid; protected void Page_Load
pdf password online; pdf password encryption
Thefirst questiontheinstaller
willask youiswhetheryou
want to install Python3forall
usersor just for you.The
default choice is“install forall
users,” whichisthe best
choice unless youhave a good
reasonto choose otherwise.
(One possible reasonwhyyou
wouldwant to “install just for
me” is thatyouare installing
Pythononyourcompany’s
computer and youdon’thave
administrative rightsonyour
Windowsaccount.But then,
whyareyouinstalling Python
without permissionfrom your
company’s Windows administrator?Don’tgetme introublehere!)
Click the
Next
buttonto acceptyourchoiceofinstallation type.
6
Next, the installerwill prompt
youto choose adestination
directory. The default for all
versions ofPython3.1.xis
C:\Python31\
,whichshould
workwell for most users
unless youhave a specific
reasonto changeit. Ifyou
maintaina separate drive letter
forinstallingapplications,you
canbrowseto it using the
embeddedcontrols,or simply
type the pathname inthe box
below. Youarenot limited to
installing Python onthe
C:
drive;youcaninstall itonany
drive,inanyfolder.
Click the
Next
buttonto acceptyourchoiceofdestination directory.
7
Thenextpage looks
complicated, butit’s not really.
Like manyinstallers,youhave
the optionnot to install every
single component ofPython3.
Ifdisk spaceisespeciallytight,
youcanexclude certain
components.
◦ RegisterExtensions allows
youto double-click Python
scripts (
.py
files)andrun
them. Recommendedbut not
required.(Thisoptiondoesn’t
require anydisk space,so
there islittle pointin
excluding it.)
◦ Tcl/Tk isthegraphicslibraryusedbythe PythonShell, whichyouwill use throughoutthisbook.Istrongly
recommendkeeping thisoption.
◦ Documentation installsa helpfile thatcontainsmuchoftheinformationon
docs.python.org
.
Recommended ifyouare ondialuporhave limited Internetaccess.
◦ UtilityScripts includesthe
2to3.py
scriptwhichyou’ll learnabout
later inthisbook.Requiredifyouwant
to learnabout migrating existing Python 2codeto Python3.Ifyouhave no existing Python2code,youcan
skipthisoption.
◦ Test Suite isa collectionofscripts used to testthePythoninterpreteritself. We willnotuseitinthis
book, norhave Ieveruseditinthe course ofprogramming inPython.Completelyoptional.
8
Ifyou’reunsure how much
disk space youhave,click the
Disk Usage
button.The
installer will list your drive
letters, compute howmuch
space isavailable oneach
drive,andcalculate howmuch
wouldbe leftafter installation.
Click the
OK
buttonto return
to the“Customizing Python”
page.
Ifyoudecide to excludean
option, selectthedrop-down
button before the optionand
select“Entire feature will be
unavailable.” For example,
excluding the testsuite will
save youawhopping 7908
KB
ofdiskspace.
Click the
Next
buttonto
accept yourchoice ofoptions.
9
Theinstallerwillcopyallthe
necessaryfilesto yourchosen
destinationdirectory. (This
happens so quickly, Ihadto
tryit three times to evenget
ascreenshotofit!)
Click the
Finish
buttonto
exit the installer.
10
Documents you may be interested
Documents you may be interested