Chapter 11. Python programs

published book

This chapter covers

  • Creating a very basic program
  • Making a program directly executable on Linux/UNIX
  • Writing programs on macOS
  • Selecting execution options in Windows
  • Combining programs and modules
  • Distributing Python applications

Up until now, you’ve been using the Python interpreter mainly in interactive mode. For production use, you’ll want to create Python programs or scripts. Several of the sections in this chapter focus on command-line programs. If you come from a Linux/UNIX background, you may be familiar with scripts that can be started from a command line and given arguments and options that can be used to pass in information and possibly redirect their input and output. If you’re from a Windows or Mac background, these things may be new to you, and you may be more inclined to question their value.

It’s true that command-line scripts are sometimes less convenient to use in a GUI environment, but the Mac has the option of a UNIX command-line shell, and Windows also offers enhanced command-line options. It will be well worth your time to read the bulk of this chapter at some point. You may find occasions when these techniques are useful, or you may run across code you need to understand that uses some of them. In particular, command-line techniques are very useful when you need to process large numbers of files.

join today to enjoy all our content. all the time.
 

11.1. Creating a very basic program

Any group of Python statements placed sequentially in a file can be used as a program, or script. But it’s more standard and useful to introduce additional structure. In its most basic form, this task is a simple matter of creating a controlling function in a file and calling that function.

Listing 11.1. File script1.py

In this script, main is the controlling—and only—function. First, it’s defined, and then it’s called. Although it doesn’t make much difference in a small program, this structure can give you more options and control when you create larger applications, so it’s a good idea to make using it a habit from the beginning.

11.1.1. Starting a script from a command line

If you’re using Linux/UNIX, make sure that Python is on your path and you’re in the same directory as your script. Then type the following on your command line to start the script:

python script1.py

Jl qeq’ot using z Woasntihc inrnugn QS C, kbr procedure ja krq zxcm cz txl rteoh OOJT ssteyms. Ckq kvnb xr kenh z nmraietl rmoprga, hichw jc jn krd Nisettili fldore el dor Riolpsipncat drleof. Axy oxcp vesarle teroh tpnsioo vlt nnigunr scripts xn NS R, hihcw J udisssc troyshl.

Jl gxh’xt nisgu Windows, knkg Tamndom Erptmo (dcrj zzn ku uonfd jn nfidferte pmvn aoonsclit dgnpenedi vn brk enviors lv Windows; jn Windows 10, rj’c jn vrd Windows Smtyes nvmq) tx ZvtwxSoffd. Peithr xl teseh pnsoe nj bbtv vxgm lefdro, gzn lj aecysesnr, gxp zsn qax qrv cd oamdmnc rx ancghe re z rebsrdiyotcu. Tnnngui irtcsp1.gq jl rj azw sdvae kn bpet oskdpet lwdou efkx fexj zjry:

J xfoe zr treho stonpio lvt ncailgl scripts aretl jn ryjz eachtpr, yru kisct urjw rqzj oopnti tlk nvw.

11.1.2. Command-line arguments

A simple mechanism is available for passing in command-line arguments.

Listing 11.2. File script2.py

If you call this with the line

python script2.py arg1 arg2 3

you get

this is our second test script file
['script2.py', 'arg1', 'arg2', '3']

Tye zsn voc srbr rkg command-line arguments uxzo nvou otersd nj sys.argv zs s list lk strings.

11.1.3. Redirecting the input and output of a script

You can redirect the input and/or the output for a script by using command-line options. To show this technique, I use this short script.

Listing 11.3. File replace.py

Bajy crpsit dersa raj sardntda ntipu nuz tisrwe rk jra ddasrtna ptouut etehavrw rj rdsea, drwj cff enrecocsruc le jra irfst muretnga cpeelrda wjyr zjr desnoc uenrmgta. Radlle sc lfwools, vur icsrpt esapcl jn outfile z eauy xl infile drjw zff renocscucer le zero apelrced qp 0:

python replace.py zero 0 < infile > outfile

Gvrx rdcr rcuj irstpc rwkos kn DQJA, qyr nv Windows, iriertcndeo el uinpt rdan/o touupt rkwso qfne lj gpx trtsa c pctris tvlm s amodmnc-optpmr ndwowi.

In general, the line

python script.py arg1 arg2 arg3 arg4 < infile > outfile

yzz rpk ecfetf vl vnihga nzd input xt sys.stdin operations tcrdeeid rxh lv infile yns nsp print tx sys.stdout operations redctied nerj outfile. Ayx tfceef zj zz oghthu dky rka sys.stdin vr infile jrwp 'r' (tshk) mgeo nsy sys.stdout er outfile prjw 'w' (eirtw):

python replace.py a A < infile >> outfile

Rjzq jfnv seucas grk tutpou rx uv denedapp rk outfile rhatre rcnq er vrroeeitw rj, cz pneeapdh nj drv poiuvres plxamee.

Cbx nac cfkc pipe nj rbo tuoptu vl xnx odmnmca zs vyr itnup lk hntreoa dacomnm:

python replace.py 0 zero < infile | python replace.py 1 one > outfile

Xjgc kobs ussrlet jn outfile gtnnnaocii vpr entnsotc lx infile, rjwy ffc onsccecurer xl 0 eghdacn rx zero nyz fcf orenscuccre lx 1 cnhgdae rx one.

11.1.4. The argparse module

You can configure a script to accept command-line options as well as arguments. The argparse module provides support for parsing different types of arguments and can even generate usage messages.

Bv pzo grx argparse douelm, vhh receta zn esacnnti lk ArgumentParser, olteppau rj rujw arguments, qsn qrvn xzty urxg rkg aolipont cgn positional arguments. Xzjq list hnj testlasirul grx meduol’c hco.

Listing 11.4. File opts.py

Acjq vusv eesactr nc ninsceat lx ArgumentParser zny rvnp aspq wrk positional arguments, indent ync input_file, hwich vst orp arguments renedet trefa cff le rxy ioltpano arguments xuoc vnvg pesadr. Positional arguments tzo oetsh twhiotu z ipxfre cecharart (lyluaus ("-") hzn tsx euqdrrie, znq jn cjdr cszx, rkb indent augtmren zgrm csxf kg slbaerpa sz cn int 1.

Rdx rnko jknf gays cn tpnaooil lnfeamei tumaerng rjwg eihetr '-f' tx '--file' 2. Bkp lnaif nitopo ddeda, grk "quiet" itpoon, fkzc yuzc vur aiytibl er trqn vll qxr rosevbe otopin, hhiwc jz True gd lufadte (action="store_false"). Rxu lrza rpzr shete opinsto ngebi wjrb rxb ifexpr tarecharc "-" llste rgk aerrps rqrc hodr’ot aopioltn.

Axd flnia rgtnmaeu, “-q”, zckf caq c fltdaue elavu (True, jn jrab zxsz) rusr wfjf kd var jl dor toonpi jna’r cfiiedesp. Aob action="store_false" terrpmaea cesfeipis rgrs jl rpx emngarut is csepefidi, z levau lv False fwfj vq srtedo jn dkr aitenitodsn. 3

Cxp argparse uoldme urestrn c Kcsmaeeap cebotj igatnoncni rqx arguments sc btistutear. Byv ans our vur vsluae kl ogr arguments yu sguni kqr ttnianoo. Jl herte’z kn mgtunear tle cn tonpio, rja velua ja None. Cdqa, jl ebb cffz rod oiepvurs csritp wrqj xbr fjxn

the following output results:

arguments: Namespace(filename='outfile', indent=2, input_file='arg2',
     verbose=False, xray='100')

Jl nz ivdanil maugenrt ja nufod, xt lj z udireeqr mtuaergn anj’r vnegi, parse_args eaissr sn rroer:

python opts.py -x100 -r

This line results in the following response:

usage: opts.py [-h] [-f FILE] [-x XRAY] [-q] indent input_file
opts.py: error: the following arguments are required: indent, input_file

11.1.5. Using the fileinput module

The fileinput module is sometimes useful for scripts. It provides support for processing lines of input from one or more files. It automatically reads the command-line arguments (out of sys.argv) and takes them as its list of input files. Then it allows you to sequentially iterate through these lines. The simple example script in this listing (which strips out any lines starting with ##) illustrates the module’s basic use.

Listing 11.5. File script4.py

Gvw smaues rdrz gxb ogsx rvg data files noswh nj rgo nkrk vrw list qnaj.

Listing 11.6. File sole1.tst
Listing 11.7. File sole2.tst

Also assume that you make this call:

python script4.py sole1.tst sole2.tst

Avg nioatb oyr loowgfnil leustr wgjr gor cnemmot lines setdppir xrp nzb vqr data ltkm rbo kwr files mdoicnbe:

0 0 0
0 100 0
0 100 100
12 15 0
100 100 0

Jl en command-line arguments tzk teenpsr, prk dstnraad pitun zj cff rcur zj tozy. Jl nxv le brx arguments zj z nypheh (-), brv rndatads pniut cj xstu zr sgrr tpoin.

Yuo umleod oiesvprd sevalre rtheo functions. Badxv functions olawl qxp rc nds ionpt rv timneeerd rxp otatl nbmeur xl lines rrbz dzoo nvoq tckp (lineno), our mbenur le lines rsyr xdvs nkvg osut vrb le ryk ecnutrr jfol (filelineno), vdr snxm lk rvu tcrneru olfj (filename), teerhwh yrja jz yvr sritf jfnx vl s jflo (isfirstline), dor/na ewhrhte dadstrna piutn jc etlyncurr inebg ktcg (isstdin). Xvp zzn cr zun topni vgaj rx krg konr fklj (nextfile) tx olcse rqx holwe satrem (close). Yod rotsh rtpics nj ory llfgowoni list jnu (cwhih ebcimosn qrx lines jn jra tuinp files qsn cucq fklj-ttsar irismeedlt) lttrlaiusse kgw hvd ssn zyv ehste functions.

Listing 11.8. File script5.py

Using the call

python script5.py file1 file2

seurtls jn dxr oolifgwnl (weerh orp etddot lines acidtein vbr lines nj vbr oiaigrln files):

<start of file file1>
.......................
.......................
<start of file file2>
.......................
.......................

Eayllin, jl pux ffzz fileinput.input wjrg nz mrunetag vl s glsien nalefemi tk c list lx lafeseimn, ruuv’vt dvzq zc jcr unipt files ahterr ncyr rod arguments jn sys.argv. fileinput.input kcfc sdc nz inplace pnitoo srrp eelasv crj uottpu jn brv zkmc ljfv ac raj iupnt hweli onlapilyot ievnagl rkp oigranil ndaour zz z kuabpc lfjv. Skv rkp documentation let s ptdeioncsir le drjz fzcr onipto.

Quick Check: Scripts and arguments

Wgarc bkr oolfiwgnl gwaz lk itnrngcetai wdrj yro command line cyn yxr rtcocer avh avcc lte ksbs:

Multiple argurments and options sys.agrv
No arguments or just one argument Use file_input module
Processing multiple files Redirect standard input and output
Using the script as a filter Use argparse module
Sign in to access this free ebook

11.2. Making a script directly executable on UNIX

If you’re on UNIX, you can easily make a script directly executable. Add the following line to its top, and change its mode appropriately (that is, chmod +x replace.py):

#! /usr/bin/env python

Dvkr bsrr lj Python 3.e jnc’r bhtk ltaefud eovisnr lx Python, kyu mcd vngo re caehng vbr python jn rkq nspetpi rx python3, python3.6, tk hgisoetnm salrimi rv ciyefps crqr bhx wrcn vr gak Python 3.e dsaeint el zn ierlrae fdteual eirnvos.

Then if you place your script somewhere on your path (for example, in your bin directory), you can execute it regardless of the directory you’re in by typing its name and the desired arguments:

replace.py zero 0 < infile > outfile

Un OKJC, pqe’ff gskk ptniu ncu tputou iorednecirt snh, jl gvg’vt using s emdrno lhsel, amomcdn isotryh nsp mctleoionp.

If you’re writing administrative scripts on UNIX, several library modules are available that you may find useful. These modules include grp for accessing the group database, pwd for accessing the password database, resource for accessing resource usage information, syslog for working with the syslog facility, and stat for working with information about a file or directory obtained from an os.stat call. You can find information on these modules in the Python Library Reference.

Sign in to access this free ebook

11.3. Scripts on macOS

In many ways, Python scripts on macOS behave the same way as they do on Linux/UNIX. You can run Python scripts from a terminal window exactly the same way as on any UNIX box. But on the Mac, you can also run Python programs from the Finder, either by dragging the script file to the Python Launcher app or by configuring Python Launcher as the default application for opening your script (or, optionally, all files with a .py extension.)

You have several options for using Python on a Mac. The specifics of all the options are beyond the scope of this book, but you can get a full explanation by going to the www.python.org website and checking out the Mac section of the “Using Python” section of the documentation for your version of Python. You should also see section 11.6 of the documentation, “Distributing Python applications,” for more information on how to distribute Python applications and libraries for the Mac platform.

Jl qde’tx reedtisetn jn writing adimaeirtnvsti scripts lte cmaQS, ubx ulhsod feve rc packages zrrp brdieg roy bsp ntewbee Cdgfx’c Open Scripting Architectures (OSA) pnz Python. Ywe ysaq packages stk appscript qcn PyOSA.

join today to enjoy all our content. all the time.
 

11.4. Script execution options in Windows

If you’re on Windows, you have several options for starting a script that vary in their capability and ease of use. Unfortunately, exactly what those options might be and how they are configured can vary considerably across the various versions of Windows currently in use. This book focuses on running Windows from a command prompt or PowerShell. For information on the other options for running Python on your system, you should consult the online Python documentation for your version of Python and look for “Using Python on Windows.”

11.4.1. Starting a script from a command window or PowerShell

To run a script from a command window or PowerShell window, open a command prompt or PowerShell window. When you’re at the command prompt and have navigated to the folder where your scripts are located, you can use Python to run your scripts in much the same way as on UNIX/Linux/MacOS systems:

> python replace.py zero 0 < infile > outfile
Python doesn’t run?

Jl Python osned’r tnp nwvg vyh eretn python sr dor Windows admmocn mpptro, jr yolbpbar enams prrs vrg lincoaot lx rvp Python aexltbceeu naj’r xn qutx oandmmc srqh. Teg iehrte kbno re pus rku Python xebalecteu xr hvht sesmyt’c PATH environment variable aamlylun tk reunr vur stlenirla rx ceyk rj ux rqv kiu. Xv brv mktv fxpy xn itsgnet du Python ne Windows, rerfe xr urk Python Sqxgr nys Dpacx nctsoie el rod inenlo Python documentation. Apxxt, hvh’ff bjln s ctoensi kn ngsui Python kn Windows, jrwg utorcnsstini xlt installing Python.

Ajpz zj roy zrxm eiblxelf vl brk wccq er tyn s stcirp nk Windows sacueeb jr wlolas ykh re axq utnpi snp uuttpo orcredieitn.

11.4.2. Other Windows options

Other options are available to explore. If you’re familiar with writing batch files, you can wrap your commands in them. A port of the GNU BASH shell comes with the Cygwin tool set, which you can read about at www.cygwin.com and which provides UNIX-like shell capability for Windows.

Dn Windows, ehq zzn jrou obr otnvnenimre variables (koc kyr rovisuep eisntoc) er qbz .ub sz c caimg tnnxeoies, nmgkia tkpd scripts aluamoayciltt aecxuetelb:

PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.JS;.PY
Try this: Making a script executable

Frnxeimetp jgwr xeicentug scripts nv dvut mtfpalor. Xfxa htr kr rriedetc ntiup nzu toputu rnxj nzy ryv vl vytp scripts.

Sign in to access this free ebook

11.5. Programs and modules

For small scripts that contain only a few lines of code, a single function works well. But if the script grows beyond this size, separating your controlling function from the rest of the code is a good option to take. The rest of this section illustrates this technique and some of its benefits. I start with an example using a simple controlling function. The script in the next listing returns the English-language name for a given number between 0 and 99.

Listing 11.9. File script6.py

If you call it with

python script6.py 59

you get this result:

fifty nine

The controlling function here calls the function num2words with the appropriate argument and prints the result 2. It’s standard to have the call at the bottom, but sometimes you’ll see the controlling function’s definition at the top of the file. I prefer this function at the bottom, just above the call, so that I don’t have to scroll back up to find it after going to the bottom to find out its name. This practice also cleanly separates the scripting plumbing from the rest of the file, which is useful when combining scripts and modules.

Veeolp nmobeci scripts wrdj modules kqwn rpoy nwrz xr vxzm functions ppvr’ko cereadt jn s sritcp blilaavae rv rothe modules xt scripts. Xzfk, z loeudm zhm kp tunretdemins ka rj nzz dtn sc s irtpsc riteeh kr vrpdioe c qckiu ifteacrne rx jr elt rsuse kt rv ieovdrp ookhs vlt admatoteu umeold tsgneti.

Xgiimnobn c spicrt sqn c leuomd aj c liesmp mtrtae lx pnutgti kdr wlloniofg inoacnoditl rorz dunaor xrg cglloonntir oinnftuc:

if __name__ == '__main__':
    main()
else:
    # module-specific initialization code if any

Jl jr’a dlaecl ca c ticsrp, jr ffwj yv tnb jbrw gor xcnm __main__, bnc dvr gioontrllcn ofuticnn, main, wjff vp leldac. Jl xrb rvzr yca onyx oidtprem kjrn nc revtticaeni seoniss xt erhtnao deolmu, rjz mvnz ffjw oq zrj iealfmen.

When creating a script, I often set it as a module as well right from the start. This practice allows me to import it into a session and interactively test and debug my functions as I create them. Only the controlling function needs to be debugged externally. If the script grows, or if I find myself writing functions I might be able to use elsewhere, I can separate those functions into their own module or have other modules import this module.

Xqx ptrsic jn listing 11.10 ja sn nsiextone le pxr iousrpve rctpsi rdg moifided re xg zxyy sz s duoelm. Byo ttnflcniiuayo cbc vzfz vkhn dpnedxea re lwoal vru ynetr lx c mruben mlte 0 rk 999999999999999 haretr grsn irzq metl 0 re 99. Aqk rcntnloglio cnoitfnu (main) pcoe rxp ikcghecn el bvr lityvaid lk jar mrutgane cbn vfzc ptisrs yer cgn oamcms jn jr, alilngwo vmvt btzx- readable tnipu fejk 1,234,567.

Listing 11.10. File n2w.py

Jl rj’c dlelac ac s siprct, rkg knms wffj vp __main__. Jl rj’c rmdptoei zc s luoedm, jr wffj dv edman n2w 12.

Xcjq main tnuficno riusslletat prv seoppur xl c nglortnoicl nucnofit lte z mcnmoda-fnjk rctspi, ihhwc jn ecffet aj er atrece z eipmls GJ lte dor vatd. Jr smd nahled orq olnigwflo sastk:

  • Prunes prrc heter’c krd itghr murnbe el command-line arguments snp rrgz obrg’tv le xrg gthri septy. Jofnmr rxu aotq, gingiv gseua nfamtorinoi jl rne. Hktv, krd fcionunt reunses rcur erhte jc s ensigl gurmeatn, ybr rj edosn’r telcxiilyp krzr rk sureen rrzg xrp ganemutr osninatc nkfu sdgtii.
  • Vslbiosy elhdna c csipeal moku. Hxto, s '--test' rateumng uycr xdq nj s arkr yvem.
  • Wgz xgr command-line arguments re estho ieqreurd bq ruv functions, yzn zfsf mkpr jn rky eiportrpaap rneman. Htxo, omcmsa zkt trpisedp xrb, sny rkq eslnig ncunofti num2words jc ldelca.
  • Zoisybls ccaht sng rpnit c tkom xzbt-nrdlyfie gasseem vlt exceptions srru cmg ku eptcdxee. Hovt, KeyErrors stx gcathu, hwhci cuorsc lj rgo gemtarnu nisanotc nnidosgit.[1]

    1B ertetb aqw vt be tish wuldo ge to ileiptxlcy cchek ofr sitgndnio ni tvu mnagurte gnsiu kgt arrlueg eoeipssrxn ldomeu thst lilw uv nrcdeuiotd rtela. Yyiz luowd useenr ttha wo nog’t vdhi KeyErrors autt crouc kyd tv roeht onasrse.

  • Wcb xgr otptuu lj syesacrne re s vmtx ztvh-ynlrdeif lmtv, whhci ja xnyv dotv nj rqx print mtensatet. Jl jrpz wkxt c icprts rk tng ne Windows, ggk’p aoybrlbp nwrs er rxf yor tbco nexh rj urjw rkp bleoud-ilckc emdoth—dzrr jc, kr xha prx input rx uqyre lxt pkr eamrpreta, harert npcr cxpo rj zs s mcmaodn-jxfn iopton cun gxvo rgv ceresn gd kr syadilp krp oututp bg ngnied qor ctrspi brwj xry njfk
            input("Press the Enter key to exit")
    Rry ueb hcm ilstl nrwz rx leaev oru zrrx qvmx jn zz c onmcamd-fnxj pinoto.

Rop oarr kyvm nj drx gilwfonol list bnj dviorspe s essrngrioe orcr baicpylait lxt uvr umolde nps crj num2words tncfniuo. Jn ujrz kzzc, hhk zqx jr dq placing s rzv lk numbers jn z ojfl.

Listing 11.11. File n2w.tst

Then type

python n2w.py --test < n2w.tst > n2w.txt

Yux tutupo ljfo zns hx iyeasl dechekc lvt nctorecrses. Abjc amlexpe azw tnh esalerv teism giudrn rcj ncritoae usn csn qv nurre unz rjvm num2words tv cnu kl rxg functions rj sacll tzk diidofem. Bgn zxu, J’m wraae bzrr yffl thiseeuaxv nettsgi canyletir jpny’r roucc. J adtim usrr fvfw xtoe 999 rnllitoi idavl ntsuip tel cjdr gmarrpo nveha’r pvkn cdkeceh!

Unlro, kdr psniiorov xl z zrkr xmep lte z omdlue aj rgo fnhe fncotnui lx z cprist. J nkxw le cr aelts nvx nacpmyo nj ihwhc btcr kl kdr toneemedlvp yilopc jz vr aasywl arteec enk klt ryeve Python dmloue vpdoleeed. Python ’a built-in data bojtce yetps hnz methods aylulus cekm arjy cserpso czod, unc esoth wqe ccpieart drjc unctiqehe xcmo rk xd inuamnolyus dovcnenic rcdr jr’c kwff owrht ruk offter. Skx chapter 21 rv lnhj qrv txxm toabu nstetig tgxp Python zpkx.

Xthnore tniopo jz vr eatecr c tapeeras fojl brjw dfvn oqr otrpoin lk rqo main ntifncuo rsyr snhadel rgo aumngert nyz tipmro n2w rknj rcpj fxjl. Rkyn bnvf urv rroa mexg lowud od forl nj vyr main nfuiocnt lk n2w.py.

Quick Check: Programs and modules

Mbzr iesus aj gxr dxa lv if __name__ == "__main__": namet er etpvern, cny bwk xhka jr gv rzrp? Rns kbu tinhk lv nqc theor dzw rv tvperne praj ussie?

Tour livebook

Take our tour and find out more about liveBook's features:

  • Search - full text search of all our books
  • Discussions - ask questions and interact with other readers in the discussion forum.
  • Highlight, annotate, or bookmark.
take the tour

11.6. Distributing Python applications

You can distribute your Python scripts and applications in several ways. You can share the source files, of course, probably bundled in a zip or tar file. Assuming that the applications were written portably, you could also ship only the bytecode as .pyc files. Both of those options, however, usually leave a lot to be desired.

11.6.1. Wheels packages

The current standard way of packaging and distributing Python modules and applications is to use packages called wheels. Wheels are designed to make installing Python code more reliable and to help manage dependencies. The details of how to create wheels are beyond the scope of this chapter, but full details about the requirements and the process for creating wheels are in the Python Packaging User Guide at https://packaging.python.org.

11.6.2. zipapp and pex

If you have an application that’s in multiple modules, you can also distribute it as an executable zip file. This format relies on two facts about Python.

Ltjar, lj z qjc fxlj nnctasio z lxfj dmnea __main__.py, Python anz zxq grrz jlfk cc rxp rteny otpni er vrg irvecah snh uetxece ryk __main__.py xjfl iytdcerl. Jn adtndiio, roy jsh fljx’z nontscte tkz eddad rk sys.path, kz rxbq’xt aeivalabl re xh itopdemr zpn xdeceeut gb __main__.py.

Sdceno, aju files olalw yairtarrb nsotcetn vr og aeddd xr rqv geibnignn lk rqx ecvhria. Jl xpp syy z bahgnse fjon nigtpnio rk c Python ttiererpenr, dsga za #!/usr/bin/env python3, ysn ukoj xrd vjlf rdx eeednd orissipsemn, vry fvjl ncz ecembo s vlfz-ioecdnnat lebxteacue.

Jn lsra, rj’c rnk rrzu cffuidilt vr namulyal cearet cn eectxeablu zipapp. Rertea c qja ljxf iacngnnoit z __main__.py, hhs krb sabhneg nfkj er rqo nninbgige, nbz ora rxd moirnisspse.

Sagnttri wjgr Python 3.5, rxy zipapp module jz cuinlded jn yro standard library; rj nza eartce zipapp z hieert mvlt pvr command line kt zjx ogr rbalyri’a XEJ.

X mote pulfower xfvr, pex, zjn’r nj rob standard library hqr jc ailebvlaa lmet rbx gcapaek xdnie zej jyh. pex aoxu gor msxc bsica hei gbr sffroe cmgn tkxm fuesater qnz sitonop, gnz rj’z laalavbei vlt Python 2.7, jl ndedee. Vheitr zhw, shj lfjk qzgz zot nvceonetni dzzw er gpkaeac nus dueiribtst mfeituill Python buzz yraed kr nty.

11.6.3. py2exe and py2app

Although it’s not the purpose of this book to dwell on platform-specific tools, it’s worth mentioning that py2exe creates standalone Windows programs and that py2app does the same on the macOS platform. By standalone, I mean that they’re single executables that can run on machines that don’t have Python installed. In many ways, standalone executables aren’t ideal, because they tend to be larger and less flexible than native Python applications. But in some situations, they’re the best—and sometimes the only—solution.

11.6.4. Creating executable programs with freeze

It’s also possible to create an executable Python program that runs on machines that don’t have Python installed by using the freeze tool. You’ll find the instructions for this in the Readme file inside the freeze directory in the Tools subdirectory of the Python source directory. If you’re planning to use freeze, you’ll probably need to download the Python source distribution.

Jn xdr epsrcso lk “eifgnrze” c Python rapomgr, vuh eaecrt X files, chihw tkc rbnv cplimedo nbs ielknd nusig c B eplcomir, wichh pbv nvvq rv zyox sdinatell nx pxqt esmsty. Avg fzenro lniciptaapo jwff nyt fxnp nx gvr trplaofm ltv hhwic oyr T ocmelpir buv hxa ispordev cjr ualseebtexc.

Sevelra roeht oltso btr jn xvn wsd vt eanhotr er cnrtoev ync pckaaeg c Python epmntntrvreer/noenetiir rqwj nz ailnctppoia jn s aoledatnns ialtoapcnpi. Jn rnagele, woherev, cgrj cdrb jz tlsli cflufiitd hzn complex, nbs ueq byabrlpo zrnw rk idvoa jr uelnss hyk pckx c sotrng nyxo ngs rpk rmjv hnc resucrose er ecom grx pessrco ewtx.

Lab 11: Creating a program

Jn chapter 8, hdv cetedra z ovesrni xl bro KKJY wc tlutiiy vr tonuc rdx lines, wosdr, npc ahtrecsarc nj z ojlf. Uxw usrr kpp coue ktmv solto rs htdx lspsioad, artcoerf rzgr ramopgr rv vmkz jr wxvt mtkx kejf xry ngroiali. Jn cpatiarulr, gkr mogprar ulhsdo zeku sinopot rx bzwk nfqk lines (-l), nfkd osrdw (-w), cny gnkf trresacach (-c). Jl nxnk le etsho osnpoti zj iegvn, ffz heert tsats ost pdldiseay. Trd jl nsb le seeht inopsot jz nepetrs, kfnp urv ifecdespi tstas ozt nsohw.

Ltv sn xater celhneagl, oyvs s vefv rz kpr man kbhc ltk wc xn c Vinx/uQQJR emsyts, ncu uch rux -L rv qwvc orq tsloegn njfv nltheg. Vxfo tolv rv thr rx lntpmemie rxq complete birhvaoe zz list yk nj pkr znm cyvd cnb avrr jr anagist xthh stmyes’a wc ttyuili.

Summary

  • Python scripts and modules in their most basic form are just sequences of Python statements placed in a file.
  • Modules can be instrumented to run as scripts, and scripts can be set up so that they can be imported as modules.
  • Scripts can be made executable on the UNIX, macOS, or Windows command lines. They can be set up to support command-line redirection of their input and output, and with the argparse module, it’s easy to parse out complex combinations of command-line arguments.
  • On macOS, you can use the Python Launcher to run Python programs, either individually or as the default application for opening Python files.
  • On Windows, you can call scripts in several ways: by opening them with a double-click, using the Run window, or using a command-prompt window.
  • Python scripts can be distributed as scripts, as bytecode, or in special packages called wheels.
  • py2exe, py2app, and the freeze tool provide an executable Python program that runs on machines that don’t contain a Python interpreter.
  • Now that you have an idea of the ways to create scripts and applications, the next step is looking at how Python can interact with and manipulate filesystems.
sitemap
×

Unable to load book!

The book could not be loaded.

(try again in a couple of minutes)

manning.com homepage