Open navigation menu
Close suggestions
Search
Search
en
Change Language
Upload
Sign in
Sign in
Download free for days
0 ratings
0% found this document useful (0 votes)
61 views
92 pages
Raspberry Pi T&T8 TH 21
Uploaded by
Dragonnet Dragonnest
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Download
Save
Save RaspberryPiT&T8th21 For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
0 ratings
0% found this document useful (0 votes)
61 views
92 pages
Raspberry Pi T&T8 TH 21
Uploaded by
Dragonnet Dragonnest
AI-enhanced title
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here
.
Available Formats
Download as PDF or read online on Scribd
Carousel Previous
Carousel Next
Download
Save
Save RaspberryPiT&T8th21 For Later
Share
0%
0% found this document useful, undefined
0%
, undefined
Print
Embed
Report
Download
Save RaspberryPiT&T8th21 For Later
You are on page 1
/ 92
Search
Fullscreen
LL ae Your Codel Raspberry Pi Tricks and Tips oa isa a i 2 3 coy (- Vass TOTTI \ aN ueAre you a Windows PC user? Then don’t miss our latest essential Windows 11 user guide on Readly now! The Essentials Your essential guide to Microsoft's new Windows 11 operating system oo LX) ec at | | | = Discover new uses ‘and functionality with | an step-by-step guides | Windows 11 update Essential tutorials | All your questions @ insider tips for the | about Windows 11 are answered insideRaspberry Pi i ial a Welcome back... Having completed our exclusive For Beginners digital guidebook, we have taught you all you need to master the basics of your new device, software or hobby. Yet that’s just the start! Advancing your skill set is the goal of all users of consumer technology and our team of long term industry experts will help you achieve exactly that. Over this extensive series of titles we will be looking in greater depth at how you make the absolute most from the latest consumer electronics, software, hobbies and trends! We will guide you step-by-step through using all the advanced aspects of the technology that you may have been previously apprehensive at attempting. Let our expert guide help you build your naa out journe, ees &y Continues, understanding of aie we will be with you technology and gain the “ey Stage to advice skills to take you from a inform and ultimatol,” confident user to an inspire you to experienced expert. 90 further.Contents 6 Python Code & Ideas Pane nee 16 10 Number Guessing Game iT Pam eiticicr Ft rmsd 22 Mastering Linux eee 46 POM rasa ec Prete an eta balcd od 30 Creating and Deleting Files 50 Ermer Wea Deierlu cet
File and save tas FileMan.py. Once executed it will display the program title, along with the current time and date and the available options. import shutil import os Amport tine import subprocess et Resd() ‘patheinput(Enter the file path to read:”) ‘le=open(path,"r") printiile reed()) Anput('Press Enter. le.close() det write) ‘path=input(Enter the path of file to write or create:") Af of. path issile(path): print(‘Rebutlding the existing Ale’) ote rint((Creating the new fle’) textainput("Enter text:") ‘leropen(path,"w") Sle.writa(text) det ada ‘path=input Enter the Sle path:") texteinput("Enter the text to adds") ‘leropen(path,"2") ‘Sle writa(‘\n'stext) det delete) ppath=input("Enter the path of file for deletion:”) Lf os path existe(path) rint(‘File Found’) os.renove(path) pEint(‘File has been deleted’) ete: ‘Print(‘File Does not exist’) det Dirlist) ‘path=input( Enter the Directory path to display:”) sortlistascrted(es.1istdir(path)) while (Sclen(sortiiet) ‘peint(eort]ist[s}+/\e") Sel det check: ‘print{input{'Check existence of \nl.File \n2 Directory\n’)) Le pests ppath=input("Enter the file path:") Of. path. Sefile(path)Af os.path defile (path)==True: rint((File Found’) eint(‘File not found’) Af p= patheinput("Eater the directory path:”) os.path-isdiz(path) Sf of. path, Sedir(path)=Fal print(‘Directory Found’) euse: Peint(‘Directory Not Found’) det Hove): ‘pathisinput(‘Enter the source path of file to nove: ‘ar=int (input("I Rename \n2.Move \n) Af meet: ‘ath2einput(Enter the destination path and fle name’) shutil.move pathl,path2) peint('File renamed’) sf m=?) [path2=input( ‘Enter the path to move:’) shutil.move pathi,path2}) Print('File moved’) det copy(): pathlsinput( ‘Enter the path of the file to copy or renames") path2=input(‘Enter the path to copy to:") sthutil.copy (path path2) rint('File copied’) det Makedix(): path=input("Enter the directory name with path to make \neg. C:\\seiio\\owdir \nihere Nowdix is new directory") os makedixe(path) rint((Directory Created’) et Renovedix() path=input(‘Enter the path of Directory:") tereedireint(input('L Deleted Directory \n2.Delete Directory Tree \n3.Exit \n’) Sf troedir==i os.zndir(path) Af treedir==2 hati mtree(path) peint(‘Dizectory Deleted’) Af treedixe=t: exit) def opentile(): [path=input( ‘Enter the path of progran: ey: os.startéle(path) ‘except: ‘peine('FLle not found’) re ‘tietuom = = onyetent cle) = a Seeysten(cle? print yoomoooonytion 3 de Manager) ise(tm clout lian and ata arise sina Set ecee ete Enerin inact" htae «Re aueite wo ale Sepend tent fo 0 le ‘Dela « fe Python File Manager S.List files in a directory G.check fle existence Move a file 8.copy a file S.czeate 2 dizectory iO.Delete a directory 3L.0pen a program Preset vm Af dec=: Readi) Af decom weite() Af dace dao Af dec=nt: af Dirlist) Af decené: Check’) Move() Af decom copy) Af decm=d: Makedix() Af dec=0: Renovedir() Af dec==il Opensite() Af dece=i2 exit) unsint(input("L Return 0 menu\n2.Exit \a")) Af rune exit) Imports There are three modules to import here: Shull, OS and Time. The First two deal wth the operating system and file management and manipulation; and the Time module simply displays the current time and date. Note how we've included a try and except block to check iF the users running the code ona Linux system or Windows. Windows uses CLS to clear the screen, while Linux uses clear. The try black should work well enough butt'sa point of possible improvement depending on your own system. wnebdmpubleatonscom — 81el Ee eee ees i Number Guessing Game SSR teet ec but it makes good use of the Random Date aa ae While loop. The number of guess can be increased from 5 and the random number fange can easily be etched NUMBERGUESS.PY Copy the code and see if you can beat the computer within Five ‘guesses. I's an interesting bit of code that can be quite handy when your implementing a combination of the Random module alongside a while loop. import random guesseatsed = 0 Nane=input(‘Hello! What is your nane? *) number = random.zandint(1, 30) print((Greetings, ‘+ Name +‘, 1m thinking of a number between 1 and 30.’) while guessestsed < 5: ‘quess=int{input(‘Guess the munber within 5 guesses...)) quessesUsed = guessesUsed + 1 Sf guess < number: rint(‘Too low, try again’) Af guess > number: eint ("Too high, tey again.”) Af guess == number: break Print('Well done, "+ Name + ‘! You guessed correctly in * + guessestsed + * quesses.’) Af guess != number: ‘number = str(nunber) Print((Sorry, out of guesses. The number I wi thinking of is + number) ‘Although thisisa reasonably easy to follow program, there are ‘some elements to the code that are worth pointing out. To begin with, you need to import the Random module, as you're using random numbers within the code. ‘Thissection of the code creates the variables forthe number ‘of guesses used, along withthe name ofthe player, and also sets up the random number between 1 and 30. Fyouwant a wider range of random number selection then increase the rnumber=random.randint(1, 30) end value of 30; don't make ittoo high though or the player wil never be able to quessit If the player uesses too low or too high they are given the ‘appropriate output and asked to try again, while the number ‘of guessesis less than ive, You can also increase the number oF ‘guesses from 5 by altering the while quessesUsed <5: value, IF the player uessed the correct number then they are given a ‘well done’ output, along with how many quesses they used up. iF te player runs out of guesses, then the game over output is
>>;p>9>>>Awesome Adventureccccccccc<\n") print("\n" * 3) time. sleep(3) print(*\aA long time ago, a warrior strode forth from the frozen north.") ‘tine. sleep() print(‘Does this warrior have a nane?”) ame=input (">") print(nane, “the barbarian, sword in hand and looking for adventure!") ‘tine. sleep() print(*Hovaver, evil ie lurking neazby....") z= print(Will”, name, “prevail, and win great fortune...") time. sleep(1) print(‘Or die by the hands of great evil...2") ‘time.aleep(]) print("\a" #3) print(‘Omly time will tell...”) ‘ime. aleep(2) print’. teime.alé print{( print("\a" #200) print(” You find yourself at a small inn. There's Little gold in your purse but your sword is sharp, land you're ready for adventure, With you are three other customers, A ragged looking man, and a pair of dangerous looking guards.'") det start() peint(*\n — ppEint(‘Do you approach the...”) print (“\n") rint(‘1. Ragged looking man”) rint(‘2, Dangerous looking guards”) endlist=['2", "2" ‘endsgetond(cndlist)Adventure Time This, as you can see, isjust the beginning ofthe adventure and takes up a fair ew lines of code. When you expandit, and weave the story along, youll Find that you can repeat certain instances suchas a chance meeting with an enemy or the ike. We've created each of the two encounters as a defined set of Functions, along with alist of possible choices under the cmalist ist, and cma variable, of which isalso a defined Function. Expanding on thisis quite easy, just map out each encounter and choice and create a defined function around it. Providing the user doesr't enter quit into the adventure, they can keep playing. There's also room in the adventure Fora set of variables designed For combat, luc, health, endurance and even an inventory or amount of gold earned. Each successful combat situation can Feduce the main character's health but increase their combat skills or endurance. Pus, they could loot the body and gain gold, crear gold through quests. Finally, how about introducing the Random module. This will tenable you to include an element of chance inthe game. For cexampie, in combat, when you strike an enemy you will do.a random amount of damage as willthey. You could even work out the maths behind improving the chance ofa better hitbased on your or your opponent's combet sls, current health strength and endurance. You could create a game of dice in the inn, tose iF you win or lose gold (again, improve the chances of winning by working out your luck actor into the equation) Needless to say, your text adventure can grow exponentially and prove to be a work of wonder. Good luck, and have Fun with your adventure, | Text Adventure Script det gotcnd{endlist): fend = input{nanet’>”) Af ond in ondlist: return ond ‘elif ond = “help”: [PEint("\aEnter your choices as detailed in ‘the gane.”) print(Yor enter ‘quit’ to leave the game") return gatond(cndlist) (elif end = “quit”: peint ("\n—= ‘time. sleep(2) Print(Sadly you return to your homeland without, fame or fortune...") 7 ‘time.sleep(5) exit) if __name__=" sareo wubdmpubcavonscom 85Een Code and res i Python Digital Clock A oer Cee Ne oe as secon Riera nO messes CRC) butit’s always handy to have one‘on top Caren a UALS at er Ngee cy uence Cement Seoul areata Mesos atl DIGCLOCK.PY This is a surprisingly handy litle script and one that we've used in the past instead of relying on a watch or even the clockin the system tray ofthe operating system. import time import tkinter as tk def tick(timel=") # get the current time from the FC tine? = tine. stretime HH: R1S') Sf time? '= timel: timel = tine? clock.contfig(text=time2) clock.after(200, tick) root = tk.tk() clock = tk.Label(root, font=('ariaY’, 20, ‘belé’), 2bg='green’) clock pack{Gll="both’, expands) tick) root.aintoop()Tick Tock Thisis apiece of code we've used mary times inthe past to keep track of time while working on multiple monitors and with usta uick glance to where we've placed iton the screen The Tkinter box can be moved around without affecting the time, maximised or closed by the user at will We havertt given the Tkinter clock window title, so you can add to that easy ‘enough by snipping the code from other examples in this book Another area of mprovementis to include this code when Windows or Linux starts, soit automatically pops up on the desktop. See aso, f you're able to improve its Functionality by including different time zones: Rome, Paris, Landon, New York, Moscow and soon. Another example, expanding on the original code, could bea digital stopwatch. For that you could use the Following Amport teinter Amport tine class Stoptiatch tkinter. Frame) ectassmethod ‘def main(cle) ‘kinter.NeDefaultRoot() root = tkinter.7k() | Python Digital Clock zoot-titie('Stop atch’) root.resizable(trve, False) root.grid__coluanconfigure(0, weight=I) padding = diet(padees, pady=s) widget = Stopatch (root, *¥padding) widget grid(eticky=tkinter.NSOY, “¥padding) root-maintoop() det __ init__(self, mastersone, onf=(), *#ky) padding = dict(padetorpop((pedk’, 5), pady=bw, pop’pady’, 5) super().__init __ master, nf, *kx) selé.grid_colunnccnsgure(1, weight=l) self.grid_ roweontigure(t, weight=1) self. _total = 0 abel = thinter Label(eete, ____ tine = tkinter Stringvar(eelé, 8.680000" self. _ _display = tkinter-tabel (self, det __click(eeis) Af eal. _ _buttont‘text’) == ‘start’: sole, _ _batton{‘text’] = ‘stop’ sele, _ _start = tine.clock) self. _ leounter = selé.atter _dle(self. else: self. _ _button{‘text’] = ‘start’ self-after_cancel(self._ _counter) —vpdate) dof _ _vupdate(eaie) now = time.clock() ie = now ~ self. ele. _ total += ditt self, _ _ tine.cot('(:.6)format(eoif. __total)) tele, _ eounter = selé.atter _idleleelé._ _ update) sare wu bdrmpublcatons com 87& Een rene Vertically Scrolling Text ‘What's not to like about vertically scrolling text?.Its uses are many: the em pacte mcrae ata) Something épic, like the beginning of CNA eT eae oe Mecit accuse er io ac Peroni cle Ra eke EPICSCROLL.PY (We've used the poem Cimmeria by Robert E. Howard For the code's scrolling text, along with a dramatic black background and red text. We think you'll agree, i's quite epic. Amport pygane as pg from pygame.locals import * pg.tnseo text _list = 1 remember The dark woods, masking slopes of sonbre hills; ‘grey clouds’ leaden everlasting arch: e dusky streams that flowed without a sound, [And the lone winds that whispered down the passes. Vista on vista marching, hills on hills, Slope beyond slope, each dark with sullen trees, ‘Our gaunt land lay. So when a man climbed up ‘A rugged peak and gazed, his shaded eye Saw but the endless vista ~ hill on hill, Slope beyond slope, each hooded like its’ brothers, Tt was a gloomy land that seemed to hold [ALL winds and clouds and dreams that shun the sun, With bare boughs rattling in the lonesome winds, And the dark woodlands brooding over all, Not even lightened by the rare dim sun Which made squat shadows out of men; they called st Cinmeria, land of Darkness and deep Night. Te was so long ago and far away T have forgot the very nane men called ne. The axe and fint-tipped spear are like a drean, And hunts and wars aze shadows, I recall Only the stillness of that sombre land; The clouds that piled forever on the hills, ‘he dinness of the everlasting woods. Cimmeria, land of Darkness and the Right, (Oh, soul of mine, born out of shadowed hills, To clouds and winds and ghosts that shun the sun, How many deaths shall serve to break at last This heritage which wraps me in the grey Apparel of ghosts? T search my heart and Sind Cimmeria, land of Darkness and the Hight! vr gphst cn’)clase Credits: def __ init__(self, screen _rect, 1st): self erect = ecreen _ rect pele let = Let jelf.eize = 16 self.color = (255,0,0) ‘self butf_centery = self.srect.height/2 + 5 elf buff _ lines = 50 self-tiner = 0.0 self-delay = 0 jelf. make _ surfaces() def make _text(self message): font: = pg.font.SysFont("Arial’, self.size) ‘text = font.render(nessage,True,sel£.coloz) rect = text.get _ rect (center = (self.srect. conterx, self.srect.centery + self.butf _centery) ) return text rect for i, Line in enunerate(self.1st): 1 = self.make_ text(Line) py += iselE butt Lines E.text.append(l) def update(sels): Af pg.tine.get _ ticks()-self.timer > self.delay: e.timer = pg.tine.get _ticks() for text, rect in self.taxt: recty = 1 def render(self, surf): for text, rect in self.text: ‘surf.blit(text, rect) screen = pg.display.set _ mode((800,600)) screen _ rect running=true ered = Credits(screen rect, text _ list) while cunning: for event in pg.event.get(): Af event.type == QUIT: running = False screen £11((0,0,0)) ‘cred.update() ccred,render(screen) Pg.display.update() ‘clock. tick(60) Vertically Scrolling Text ALLong Time Ago.. The obvious main point of enhancement is the actual text self. Replace It with alist of credits, or an equally epic ‘opening storyline to your Python game, andi will certainly hitthe mark with whoever playsit. Don't forget to change the screen resolution if needed; were currently running feat 800 x 600. 89Een Code and res i} Text to Binary Convertor While it may not seem too exciting, this TXT2BIN.PY Mee eee Naturally we're using the Format function to convert the ORNS AMMEN GMM ccs entered text string tots binary equivalent you SoC CORCLRECUTINO Mor {0 eck ts 2cuaeyyoucan lug the binary nto an Moline textsinput("Enter text to convert to Binary: ") print(’ ‘join(format(ord(s), ‘b’) for x in text)) Seo aaa st File Edit Format Run Options windows Help print¢ ) text=input( ) print(* *.join(format(ord(x), text))1000010 1101001 1101110 1100001 1110010 1111001 The text to binary convertor does offer some room for improvement and enhancement. There are many uses:it could be utilised ina password or secret word script, as part of an adventure game or just a novel way to display someone's name. \With regards to improvements, ou could display the binary cenwersion ina Pygame window, using the animated text options From page 100, You could also ask the user if they wanted to have another go, or even askif they wanted the binary outputto be saved toa file, \With regards to rendering the outputted binary corwersion toa Pygame window, complete with rotating text, you can use: smport pygane ygane.inito BLACK = (0, 0, 0) ITE = (255, 255, 255) ‘BUM = (, 0, 258) GREEN = (0, 255, 0) RED = G55, 0, 0) Print (>oospesppptext to Binary Convertor
opppoppppilangmancecececeeedet guess{self,letter): Af letter in selfword and letter not in self. (guessed _ letters: If guessed _ lettere.append(letter) elif letter not in self word and letter not in self.mised letters: sf missed _ letters append(letter) for letter in self.word: Af letter not in self.guessed _letters: inte else: tn += letter return tn def print _ game _status(selé): Print (board{ien(self missed _ letters))) Print (Word: ° + self.hide_word)) print (‘Letters Missed: ) for letter in self.nissed _ letter print (letter,) print () Print ("Letters Gues for letter in self.guessed_ letters: print (letter,) Print () def rand _word(): bank = “ability about above absolute accessible ‘accommodation accounting beautiful bookstore calculator clever engaged engineer enough handsome refrigerator opposite socks interested ‘strawberry backgammon anniversary confused dangerous entertainnent exhausted impossible overveight temperature vacation scissors accommodation appointment. decrease development ‘earthquake environment brand environment necessary Hangman Game Script Auggage responsible anbassador circunstance congratulate frequent’,split() return bank{random.randint(0,len(bank))] ef main(): ‘gane = Hangman(rand _word()) while not gane hangman _ over(): ‘game.print _gane _ status() ‘user _ input = input(\nfnter a letter: ") ‘game guess(user _ input) ‘game print _ game _ status() if gane.hangman _won(): QuiT() Since this the last example in our Python code repository, we thought we'd go out witha bang and feature the hangman gallows being drawn with each incorrect quess of the word. Don't worry fit looks misaligned in the text here, this is merely de tothe differences between using the Python |DLE editor and pasting the code into a word processor (which Formats tings differenti) “There's plenty you can do to improve, enhance and expand on ‘what we've presented here, You can include aroutine that returns an errorif the user enters a number or character. You can include extra points For someone who guesses the entire ‘word n one go rather than one leer at atime and you could perhaps add Chopin's Funeral March should youlose the ‘game; or something celebratory if you win, Consider replacing the bank of words too. They're Found under the bank list, and could easly be swapped out For something more difficult IFyou download wivwcithub.com/
17/8!":@+ |=, The ull stop ()s used to create an extension toa file; usually used to indicate a filetype, such astextfiletxt or compressedfilezip, and stating ale with a full stop ‘makes tinsble. Dont use aullstop in place ofa space though tick tounderscores. We've created some files that we dont want, so how do we go about removing them? Itturns out that deleting files in your Raspberry Piis really esy, which may be a problem, so be careful EE Enter: 1 =2 to view the files in your home directory. IF you've followed the steps before then you should have three iles:"test’ “testi”, and "Testlle” We're going to get rid ofthese items because they were created as an example. EE ‘To get rid of files you use the “rm” command. Enter: im Testiite to delete the file called "Testfile” (with the uppercase"). Enter: 1s =1 and you'llFind t's gone, Where is ik? es notin the Trash or Recycle Bin, like on a Mac or Windows PC. les deleted completely and cannot be recovered. Bear this in mind and always think before deleting files. EEE We're going to use a wildcard (+ to delete our next two files, bt again thisis something you really need todo with cre Fist use Ns’ tolstthe Files and make sureit’sthe one you wantto delete. Enter: Is teat to view files that match the ‘word test” and any other characters. The" character iscalled a “wildcard” and it means any characters here, Wie see that "ls test™” matches two files: "eest” and testfle’ but nt the fle called “le. That's because Iedida’t match the “test” pat of “test. Check carefully over groups offiles you want to remove (remember you cant recover them) and replace the "s" with "rm. Enter: teat to remove both les. Finally enter: 6 to get rid ofthe confusing file& Mastering Linux Create and Remove Directories MANAGING FILES AND DIRECTORIES Now that you know how to create files, you'll want to learn how to make directories, which ae the same thing as items around, I you are more used to working with a desktop interFac EE Enter: 18 to quickly view all the directories currently in in the home location. Diectories are created using the “mkdir” command (make directon). Enter mika” testeaix to create ‘anew directoryin your home directory. Enter: Le againto see. Bez ‘The “mkdie” command is different to touch, in that it doesnt update the timestamp if you use it witha directory that already exists. Enter mkaiLe tastidtx again and yout, get the error “mkdir: cannot create directory ‘testdi File exists this can take abit oF getting used to. EE Like touch, you can create multiple directories at once with the mkeir command, Enter kas: testi tastdix3 and enter: 18. Youll now Find several directories called testa. Aso ike ils, you should know this means you cat (and really shouldnt) create directories with spaces. As with Files, use an underscore ('" character instead ofa space. Bez ‘You can create directories inside of each other using the directory path. Enter: mix" Decumants/ ‘hots to create anew directory called “photos” inside your ‘documents directory. The directory has to already exist, though, ry to center mkai articles/reports and youll get an error because there sno articles directory.Eee Tocreate a directory path you need to passin the “p>” ‘option to mkdir (which stands or “parents”. Options, if youremember, come after the command andstart witha. So enterakalx =p aeticles/reports. Enter: to view the articles diectory or Is aticles” to view the repos directory sitting inside. GETTING RID OF DIRECTORIES Create and Remove Directories 8 EE Now you're starting to get a bit more advanced, we're going to just reiterate something, In Linux the command structures always: command, option and argument, in that Corder, Te command isthe Function, next are the options (typically single letters starting with "and Finally the argument (often afi, or
to change the sort column, PressH to view ahelp page with all the commands youcanuse. EE "Now that you've got an idea of what processes are, how do you go about stopping them? Some processes runin the foreground untilyou quit them. Enter ping’ nw. google ‘emt and youl start. aping process continuously contacting Google. ‘Thissort of process runs until you press Controls EE Processes are stopped using the kill command. Enter: ‘leap 100. éto create adummy process. Enter: [BEEP #189p to find ts PID number (on ours itis 2192). Now enter ALL 2192 and the sleep process willbe stopped. Youcan alsouse [PRLLL eleep if youre sure you know the process name.& Mastering Linux Input, Output and Pipes IN, OUT, LINUX ALL ABOUT Everything on a computer is about input and output. You input things into the computer (press keys, move the mouse) and it makes. calculations and outputs content (changes the display, makes a noise, for example). Een ‘When you enter commands into Linux (in the command line), you ae using standard input and ‘output. Thisisso obvious that most people don't even think about it. You enter commands using the keyboard (thats input) and it responds tothe screen (output). This isthe regular way of doing it, which is why Its standard input and output” (often called “stdin” and “stdout” for shor) Sai eet aC Bez ‘As Far as the computer is concerned, input and output ‘canbe to and froma whole range of different sources that you might never even think about. pragram can get input From ‘other programs, from files stored on the hard drive and a whole host ‘of other area. outputs back tothe display ine, but also to files, ‘other programs and even other commands. Oem eee EE ‘You can change the standard output to something else using the >" character after your command, IF we wanted to see all the tems inthe python_games directory we could se Is-python_games". Using Is python_games> gamesixt” ‘outputs thelist oF tems toa new text fil called "gamestat EE ‘The games.txt file now contains the output from the is ‘command, You can checkit using “nano games Itan editable textile containing alte permissions, user and file ‘ize information and the names ofthe files. The output from the is ‘command, normaly displayed on the screen, wasinstead sent to this file. Press Control+X to quit nanoEee ‘So > enables you to output to files, but you can also ‘get input from afile, Make anew directory called music (mkdie mu some band names and trol¥0 to output the file Press Control+x to quit nano. i eed) ery USING PIPES EE We're going to use this text file as input to the sort command. Enter: sort < banda. txt and th ontent From the textile is used as input to sort. Because the output isnt spect he standard output (the screen) but you us gether Enter: sort < bands txt > bands_ the band names in order to ‘As wells directing input and output to and from files, you can send the output From one command directly into another. This is known as piping, and uses the pipe character“ ‘As you start to get more advanced in Linux, you begin to create more powerful commands, and cone way you do this is by using the pipe character (""). Take ee ae eset y Peal eau You can pipe commands multiple times. Enter 68 ee eg starting with “The” in alphabetical order. The output ofthe text From See ee eee eet at ey bands form the output. STEP3 De ey ere ess), but you might not have understood what's ees eet emenaee water irre eet Povarener creer onwetipe iL Sn nt ay Peper pees eeretans eco sree Cae Dee en a) Sree erm eee aa Pare rs etvereny et ry rc Brecon ere om | tees eran ates ann Tt PTT ate re are weit ee eee& Mastering Linux Fun Things to Do in the Terminal TERMINAL FUN Allthese commands are Linux-based, so not only can you use them on the Raspberry Pi but also on any of the Debian-based Linux distributions. EE ‘The first command we're going to useis it's not EEE If you've ever fancied having the computer read 2 Installed by default so enter: sudo apt-get. random fortune out to you then you're in ick install /s1. The command canberunwith s1 and when executed Raspbian requires you to install the Terminal app, Fortune, frst. Ener: dlsplays. Steam Locomotive traveling across the screen (hence’‘s!). sudo’ apt-get: install fortune, then simply enter: fortune, Entering: (note the uppercase) also works. into the Terminal to see what comes up. Fans of Star Wars even get a fix when it comes to the Bez ‘The rev command is certainly interesting, and at first Terminal. By tnking to aremate server vathe telnet what seemsa quite useless addition to the OS can, ‘command, you can watch Episode VA New Hope being played out, however, be used to create some seeminaly unbreakable passwords. albeitin ASCILTo view this spectacle, enter: sudo apt-get: Enter: ev and then type some text. Then press Enter and everything install telnet, followed by youtypedinis reversed. Press Cri+C to ext telnet towel blinkenlights.nlIF you're stuck trying to work outall the possible factors For any particular number, simply enter: ‘actor Followed by the number For example, Factor 7 doesnt offer ‘much output, whereas Factor 60 displays more, CE FREE Bere ne ecvcenheratherotadte EE errant you could potential alin the ter Start byinstaing cows. sudo apt-get install covsay then enter comsay Raspberty 4s Ace! Infact you can even output the ls command through the cow, by entering: 18 | comeay. EEE Ea EE” Further the cow element, there's even a graphical, ie. non-Terminal, cow avaliable. Instat with: sudo) apt-get: install xeoweay, then when t's installed enter ‘something similar to cowsay, such s: cowsay BOM Publications EE Fun Things to Do in the Terminal 8 EE IF you really want to expand the whole cow thing for whatever reason, then pipe the fortune command through it, with: Zoxtune | cowsay, and forthe graphical cow equivalent: fortune | xcowsay. Plus, there's always cowthink Try. EE ‘admittedly, the command ‘toile’ doesn't inspire much confidence. However it's not as bad ast ist sounds. Stat by installing it with: sudo apt-get: natal toilet, then ‘when it's installed, type something along the lines of: tokllet Davis ‘or perhaps list the contents ofthe current Folder through it, with: 1 | toilet Tipadhg tele arr youcncaly TEA) generate some decent looking graphics through it. For cramp ty thi taklet = anol =P metal Davia Youcan cntor Glut =p fore ofthe cormnd ine ergs to ound te
You might also like
Toaz - Info Coding For Beginners Using Python PR
PDF
No ratings yet
Toaz - Info Coding For Beginners Using Python PR
49 pages
Greatest Flash Stories Ever Told, The 290p CTC TPB (1991)
PDF
No ratings yet
Greatest Flash Stories Ever Told, The 290p CTC TPB (1991)
292 pages
Python - The Complete Manual PDF
PDF
100% (1)
Python - The Complete Manual PDF
133 pages
Coding With Replit Export
PDF
No ratings yet
Coding With Replit Export
421 pages
Linux Format - Ubuntu - The Complete Guide - 12 Edition 2022
PDF
No ratings yet
Linux Format - Ubuntu - The Complete Guide - 12 Edition 2022
100 pages
Python The Complete Manual 1652453990
PDF
No ratings yet
Python The Complete Manual 1652453990
34 pages
Python & C++ For Beginners - Vol. 33, 2019
PDF
No ratings yet
Python & C++ For Beginners - Vol. 33, 2019
164 pages
Creating Video Games Using PyGame
PDF
100% (2)
Creating Video Games Using PyGame
106 pages
Kali Linux Tutorial For Beginners - What Is, How To Install & Use
PDF
No ratings yet
Kali Linux Tutorial For Beginners - What Is, How To Install & Use
1 page
The Complete Python Manual (5th Edition) - April 2020
PDF
100% (1)
The Complete Python Manual (5th Edition) - April 2020
197 pages
Python Coding Tricks and Tips 16th
PDF
No ratings yet
Python Coding Tricks and Tips 16th
82 pages
Python Tricks and Tips
PDF
No ratings yet
Python Tricks and Tips
84 pages
ICT582 Topic 07
PDF
No ratings yet
ICT582 Topic 07
39 pages
15.food Ordering System
PDF
No ratings yet
15.food Ordering System
51 pages
CLASS XII COMPUTER SCIENCE NOTES Chapter 2 File Handling in Python
PDF
No ratings yet
CLASS XII COMPUTER SCIENCE NOTES Chapter 2 File Handling in Python
4 pages
Ahasas 9
PDF
No ratings yet
Ahasas 9
20 pages
How To Restore Deleted Files From The Recycle Bin
PDF
No ratings yet
How To Restore Deleted Files From The Recycle Bin
1 page
??python Tricks and Tips ?
PDF
No ratings yet
??python Tricks and Tips ?
82 pages
File Handling - 7
PDF
No ratings yet
File Handling - 7
48 pages
MyPython POO 2021V7
PDF
No ratings yet
MyPython POO 2021V7
79 pages
Python The Complete Manual First Edition
PDF
100% (6)
Python The Complete Manual First Edition
132 pages
How To Enable and Use Wake On LAN (WoL) On Windows 10 - Windows Central
PDF
No ratings yet
How To Enable and Use Wake On LAN (WoL) On Windows 10 - Windows Central
1 page
Programming For Cognitive and Brain Sciences
PDF
No ratings yet
Programming For Cognitive and Brain Sciences
207 pages
How To Customize Linux Terminal With OH MY ZSH (2023)
PDF
No ratings yet
How To Customize Linux Terminal With OH MY ZSH (2023)
1 page
6 Ways To Fix A Windows 10 Recycle Bin That Won't Empty
PDF
No ratings yet
6 Ways To Fix A Windows 10 Recycle Bin That Won't Empty
1 page
Python Tricks and Tips - 13th Edition 2023
PDF
No ratings yet
Python Tricks and Tips - 13th Edition 2023
82 pages
Python Coding Tricks and Tips - 16th Edition - November 2023
PDF
No ratings yet
Python Coding Tricks and Tips - 16th Edition - November 2023
82 pages
Iot File
PDF
No ratings yet
Iot File
10 pages
4 5771765541299558880
PDF
No ratings yet
4 5771765541299558880
497 pages
Writing Basic Security Tools Using Python: Ali Al-Shemery
PDF
No ratings yet
Writing Basic Security Tools Using Python: Ali Al-Shemery
77 pages
Coding With Replit Export
PDF
No ratings yet
Coding With Replit Export
258 pages
Python The Complete Manual
PDF
No ratings yet
Python The Complete Manual
133 pages
Python
PDF
No ratings yet
Python
91 pages
Pyexp 7
PDF
No ratings yet
Pyexp 7
3 pages
Remove Duplicates Function: 2. Magic 8 Ball
PDF
No ratings yet
Remove Duplicates Function: 2. Magic 8 Ball
5 pages
The Complete Python Manual by The Complete Python Manual
PDF
No ratings yet
The Complete Python Manual by The Complete Python Manual
197 pages
The Complete Python Manual (5th Edition) - April 2020-NoGrp
PDF
No ratings yet
The Complete Python Manual (5th Edition) - April 2020-NoGrp
197 pages
Python & C++ Guides - August 2019
PDF
No ratings yet
Python & C++ Guides - August 2019
166 pages
Python 4 Info Sec
PDF
No ratings yet
Python 4 Info Sec
77 pages
Python C For Beginners Apr 2022.sanet - ST
PDF
No ratings yet
Python C For Beginners Apr 2022.sanet - ST
80 pages
Coding For Python 37 2019
PDF
No ratings yet
Coding For Python 37 2019
164 pages
Python Notes 4pdf
PDF
No ratings yet
Python Notes 4pdf
8 pages
Fjkdhufhfishfuihffkvh
PDF
No ratings yet
Fjkdhufhfishfuihffkvh
4 pages
Invent Game With Python
PDF
No ratings yet
Invent Game With Python
436 pages