pexpect.py 76 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948
  1. """Pexpect is a Python module for spawning child applications and controlling
  2. them automatically. Pexpect can be used for automating interactive applications
  3. such as ssh, ftp, passwd, telnet, etc. It can be used to a automate setup
  4. scripts for duplicating software package installations on different servers. It
  5. can be used for automated software testing. Pexpect is in the spirit of Don
  6. Libes' Expect, but Pexpect is pure Python. Other Expect-like modules for Python
  7. require TCL and Expect or require C extensions to be compiled. Pexpect does not
  8. use C, Expect, or TCL extensions. It should work on any platform that supports
  9. the standard Python pty module. The Pexpect interface focuses on ease of use so
  10. that simple tasks are easy.
  11. There are two main interfaces to the Pexpect system; these are the function,
  12. run() and the class, spawn. The spawn class is more powerful. The run()
  13. function is simpler than spawn, and is good for quickly calling program. When
  14. you call the run() function it executes a given program and then returns the
  15. output. This is a handy replacement for os.system().
  16. For example::
  17. pexpect.run('ls -la')
  18. The spawn class is the more powerful interface to the Pexpect system. You can
  19. use this to spawn a child program then interact with it by sending input and
  20. expecting responses (waiting for patterns in the child's output).
  21. For example::
  22. child = pexpect.spawn('scp foo user@example.com:.')
  23. child.expect('Password:')
  24. child.sendline(mypassword)
  25. This works even for commands that ask for passwords or other input outside of
  26. the normal stdio streams. For example, ssh reads input directly from the TTY
  27. device which bypasses stdin.
  28. Credits: Noah Spurrier, Richard Holden, Marco Molteni, Kimberley Burchett,
  29. Robert Stone, Hartmut Goebel, Chad Schroeder, Erick Tryzelaar, Dave Kirby, Ids
  30. vander Molen, George Todd, Noel Taylor, Nicolas D. Cesar, Alexander Gattin,
  31. Jacques-Etienne Baudoux, Geoffrey Marshall, Francisco Lourenco, Glen Mabey,
  32. Karthik Gurusamy, Fernando Perez, Corey Minyard, Jon Cohen, Guillaume
  33. Chazarain, Andrew Ryan, Nick Craig-Wood, Andrew Stone, Jorgen Grahn, John
  34. Spiegel, Jan Grant, and Shane Kerr. Let me know if I forgot anyone.
  35. Pexpect is free, open source, and all that good stuff.
  36. http://pexpect.sourceforge.net/
  37. PEXPECT LICENSE
  38. This license is approved by the OSI and FSF as GPL-compatible.
  39. http://opensource.org/licenses/isc-license.txt
  40. Copyright (c) 2012, Noah Spurrier <noah@noah.org>
  41. PERMISSION TO USE, COPY, MODIFY, AND/OR DISTRIBUTE THIS SOFTWARE FOR ANY
  42. PURPOSE WITH OR WITHOUT FEE IS HEREBY GRANTED, PROVIDED THAT THE ABOVE
  43. COPYRIGHT NOTICE AND THIS PERMISSION NOTICE APPEAR IN ALL COPIES.
  44. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  45. WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  46. MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  47. ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  48. WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  49. ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  50. OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  51. """
  52. try:
  53. import os
  54. import sys
  55. import time
  56. import select
  57. import string
  58. import re
  59. import struct
  60. import resource
  61. import types
  62. import pty
  63. import tty
  64. import termios
  65. import fcntl
  66. import errno
  67. import traceback
  68. import signal
  69. except ImportError as e:
  70. raise ImportError(str(e) + """
  71. A critical module was not found. Probably this operating system does not
  72. support it. Pexpect is intended for UNIX-like operating systems.""")
  73. __version__ = '2.6'
  74. __revision__ = '1'
  75. __all__ = ['ExceptionPexpect', 'EOF', 'TIMEOUT', 'spawn', 'run', 'which',
  76. 'split_command_line', '__version__', '__revision__']
  77. # Exception classes used by this module.
  78. class ExceptionPexpect(Exception):
  79. """Base class for all exceptions raised by this module.
  80. """
  81. def __init__(self, value):
  82. self.value = value
  83. def __str__(self):
  84. return str(self.value)
  85. def get_trace(self):
  86. """This returns an abbreviated stack trace with lines that only concern
  87. the caller. In other words, the stack trace inside the Pexpect module
  88. is not included. """
  89. tblist = traceback.extract_tb(sys.exc_info()[2])
  90. #tblist = filter(self.__filter_not_pexpect, tblist)
  91. tblist = [item for item in tblist if self.__filter_not_pexpect(item)]
  92. tblist = traceback.format_list(tblist)
  93. return ''.join(tblist)
  94. def __filter_not_pexpect(self, trace_list_item):
  95. """This returns True if list item 0 the string 'pexpect.py' in it. """
  96. if trace_list_item[0].find('pexpect.py') == -1:
  97. return True
  98. else:
  99. return False
  100. class EOF(ExceptionPexpect):
  101. """Raised when EOF is read from a child.
  102. This usually means the child has exited."""
  103. class TIMEOUT(ExceptionPexpect):
  104. """Raised when a read time exceeds the timeout. """
  105. ##class TIMEOUT_PATTERN(TIMEOUT):
  106. ## """Raised when the pattern match time exceeds the timeout.
  107. ## This is different than a read TIMEOUT because the child process may
  108. ## give output, thus never give a TIMEOUT, but the output
  109. ## may never match a pattern.
  110. ## """
  111. ##class MAXBUFFER(ExceptionPexpect):
  112. ## """Raised when a buffer fills before matching an expected pattern."""
  113. def run(command, timeout=-1, withexitstatus=False, events=None,
  114. extra_args=None, logfile=None, cwd=None, env=None):
  115. """
  116. This function runs the given command; waits for it to finish; then
  117. returns all output as a string. STDERR is included in output. If the full
  118. path to the command is not given then the path is searched.
  119. Note that lines are terminated by CR/LF (\\r\\n) combination even on
  120. UNIX-like systems because this is the standard for pseudottys. If you set
  121. 'withexitstatus' to true, then run will return a tuple of (command_output,
  122. exitstatus). If 'withexitstatus' is false then this returns just
  123. command_output.
  124. The run() function can often be used instead of creating a spawn instance.
  125. For example, the following code uses spawn::
  126. from pexpect import *
  127. child = spawn('scp foo user@example.com:.')
  128. child.expect('(?i)password')
  129. child.sendline(mypassword)
  130. The previous code can be replace with the following::
  131. from pexpect import *
  132. run('scp foo user@example.com:.', events={'(?i)password': mypassword})
  133. Examples
  134. ========
  135. Start the apache daemon on the local machine::
  136. from pexpect import *
  137. run("/usr/local/apache/bin/apachectl start")
  138. Check in a file using SVN::
  139. from pexpect import *
  140. run("svn ci -m 'automatic commit' my_file.py")
  141. Run a command and capture exit status::
  142. from pexpect import *
  143. (command_output, exitstatus) = run('ls -l /bin', withexitstatus=1)
  144. Tricky Examples
  145. ===============
  146. The following will run SSH and execute 'ls -l' on the remote machine. The
  147. password 'secret' will be sent if the '(?i)password' pattern is ever seen::
  148. run("ssh username@machine.example.com 'ls -l'",
  149. events={'(?i)password':'secret\\n'})
  150. This will start mencoder to rip a video from DVD. This will also display
  151. progress ticks every 5 seconds as it runs. For example::
  152. from pexpect import *
  153. def print_ticks(d):
  154. print d['event_count'],
  155. run("mencoder dvd://1 -o video.avi -oac copy -ovc copy",
  156. events={TIMEOUT:print_ticks}, timeout=5)
  157. The 'events' argument should be a dictionary of patterns and responses.
  158. Whenever one of the patterns is seen in the command out run() will send the
  159. associated response string. Note that you should put newlines in your
  160. string if Enter is necessary. The responses may also contain callback
  161. functions. Any callback is function that takes a dictionary as an argument.
  162. The dictionary contains all the locals from the run() function, so you can
  163. access the child spawn object or any other variable defined in run()
  164. (event_count, child, and extra_args are the most useful). A callback may
  165. return True to stop the current run process otherwise run() continues until
  166. the next event. A callback may also return a string which will be sent to
  167. the child. 'extra_args' is not used by directly run(). It provides a way to
  168. pass data to a callback function through run() through the locals
  169. dictionary passed to a callback. """
  170. if timeout == -1:
  171. child = spawn(command, maxread=2000, logfile=logfile, cwd=cwd, env=env)
  172. else:
  173. child = spawn(command, timeout=timeout, maxread=2000, logfile=logfile,
  174. cwd=cwd, env=env)
  175. if events is not None:
  176. patterns = list(events.keys())
  177. responses = list(events.values())
  178. else:
  179. # This assumes EOF or TIMEOUT will eventually cause run to terminate.
  180. patterns = None
  181. responses = None
  182. child_result_list = []
  183. event_count = 0
  184. while True:
  185. try:
  186. index = child.expect(patterns)
  187. if type(child.after) in types.StringTypes:
  188. child_result_list.append(child.before + child.after)
  189. else:
  190. # child.after may have been a TIMEOUT or EOF,
  191. # which we don't want appended to the list.
  192. child_result_list.append(child.before)
  193. if type(responses[index]) in types.StringTypes:
  194. child.send(responses[index])
  195. elif isinstance(responses[index], types.FunctionType):
  196. callback_result = responses[index](locals())
  197. sys.stdout.flush()
  198. if type(callback_result) in types.StringTypes:
  199. child.send(callback_result)
  200. elif callback_result:
  201. break
  202. else:
  203. raise TypeError('The callback must be a string or function.')
  204. event_count = event_count + 1
  205. except TIMEOUT as e:
  206. child_result_list.append(child.before)
  207. break
  208. except EOF as e:
  209. child_result_list.append(child.before)
  210. break
  211. child_result = ''.join(child_result_list)
  212. if withexitstatus:
  213. child.close()
  214. return (child_result, child.exitstatus)
  215. else:
  216. return child_result
  217. class spawn(object):
  218. """This is the main class interface for Pexpect. Use this class to start
  219. and control child applications. """
  220. def __init__(self, command, args=[], timeout=30, maxread=2000,
  221. searchwindowsize=None, logfile=None, cwd=None, env=None):
  222. """This is the constructor. The command parameter may be a string that
  223. includes a command and any arguments to the command. For example::
  224. child = pexpect.spawn('/usr/bin/ftp')
  225. child = pexpect.spawn('/usr/bin/ssh user@example.com')
  226. child = pexpect.spawn('ls -latr /tmp')
  227. You may also construct it with a list of arguments like so::
  228. child = pexpect.spawn('/usr/bin/ftp', [])
  229. child = pexpect.spawn('/usr/bin/ssh', ['user@example.com'])
  230. child = pexpect.spawn('ls', ['-latr', '/tmp'])
  231. After this the child application will be created and will be ready to
  232. talk to. For normal use, see expect() and send() and sendline().
  233. Remember that Pexpect does NOT interpret shell meta characters such as
  234. redirect, pipe, or wild cards (>, |, or *). This is a common mistake.
  235. If you want to run a command and pipe it through another command then
  236. you must also start a shell. For example::
  237. child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > logs.txt"')
  238. child.expect(pexpect.EOF)
  239. The second form of spawn (where you pass a list of arguments) is useful
  240. in situations where you wish to spawn a command and pass it its own
  241. argument list. This can make syntax more clear. For example, the
  242. following is equivalent to the previous example::
  243. shell_cmd = 'ls -l | grep LOG > logs.txt'
  244. child = pexpect.spawn('/bin/bash', ['-c', shell_cmd])
  245. child.expect(pexpect.EOF)
  246. The maxread attribute sets the read buffer size. This is maximum number
  247. of bytes that Pexpect will try to read from a TTY at one time. Setting
  248. the maxread size to 1 will turn off buffering. Setting the maxread
  249. value higher may help performance in cases where large amounts of
  250. output are read back from the child. This feature is useful in
  251. conjunction with searchwindowsize.
  252. The searchwindowsize attribute sets the how far back in the incomming
  253. seach buffer Pexpect will search for pattern matches. Every time
  254. Pexpect reads some data from the child it will append the data to the
  255. incomming buffer. The default is to search from the beginning of the
  256. imcomming buffer each time new data is read from the child. But this is
  257. very inefficient if you are running a command that generates a large
  258. amount of data where you want to match The searchwindowsize does not
  259. effect the size of the incomming data buffer. You will still have
  260. access to the full buffer after expect() returns.
  261. The logfile member turns on or off logging. All input and output will
  262. be copied to the given file object. Set logfile to None to stop
  263. logging. This is the default. Set logfile to sys.stdout to echo
  264. everything to standard output. The logfile is flushed after each write.
  265. Example log input and output to a file::
  266. child = pexpect.spawn('some_command')
  267. fout = file('mylog.txt','w')
  268. child.logfile = fout
  269. Example log to stdout::
  270. child = pexpect.spawn('some_command')
  271. child.logfile = sys.stdout
  272. The logfile_read and logfile_send members can be used to separately log
  273. the input from the child and output sent to the child. Sometimes you
  274. don't want to see everything you write to the child. You only want to
  275. log what the child sends back. For example::
  276. child = pexpect.spawn('some_command')
  277. child.logfile_read = sys.stdout
  278. To separately log output sent to the child use logfile_send::
  279. self.logfile_send = fout
  280. The delaybeforesend helps overcome a weird behavior that many users
  281. were experiencing. The typical problem was that a user would expect() a
  282. "Password:" prompt and then immediately call sendline() to send the
  283. password. The user would then see that their password was echoed back
  284. to them. Passwords don't normally echo. The problem is caused by the
  285. fact that most applications print out the "Password" prompt and then
  286. turn off stdin echo, but if you send your password before the
  287. application turned off echo, then you get your password echoed.
  288. Normally this wouldn't be a problem when interacting with a human at a
  289. real keyboard. If you introduce a slight delay just before writing then
  290. this seems to clear up the problem. This was such a common problem for
  291. many users that I decided that the default pexpect behavior should be
  292. to sleep just before writing to the child application. 1/20th of a
  293. second (50 ms) seems to be enough to clear up the problem. You can set
  294. delaybeforesend to 0 to return to the old behavior. Most Linux machines
  295. don't like this to be below 0.03. I don't know why.
  296. Note that spawn is clever about finding commands on your path.
  297. It uses the same logic that "which" uses to find executables.
  298. If you wish to get the exit status of the child you must call the
  299. close() method. The exit or signal status of the child will be stored
  300. in self.exitstatus or self.signalstatus. If the child exited normally
  301. then exitstatus will store the exit return code and signalstatus will
  302. be None. If the child was terminated abnormally with a signal then
  303. signalstatus will store the signal value and exitstatus will be None.
  304. If you need more detail you can also read the self.status member which
  305. stores the status returned by os.waitpid. You can interpret this using
  306. os.WIFEXITED/os.WEXITSTATUS or os.WIFSIGNALED/os.TERMSIG. """
  307. self.STDIN_FILENO = pty.STDIN_FILENO
  308. self.STDOUT_FILENO = pty.STDOUT_FILENO
  309. self.STDERR_FILENO = pty.STDERR_FILENO
  310. self.stdin = sys.stdin
  311. self.stdout = sys.stdout
  312. self.stderr = sys.stderr
  313. self.searcher = None
  314. self.ignorecase = False
  315. self.before = None
  316. self.after = None
  317. self.match = None
  318. self.match_index = None
  319. self.terminated = True
  320. self.exitstatus = None
  321. self.signalstatus = None
  322. # status returned by os.waitpid
  323. self.status = None
  324. self.flag_eof = False
  325. self.pid = None
  326. # the chile filedescriptor is initially closed
  327. self.child_fd = -1
  328. self.timeout = timeout
  329. self.delimiter = EOF
  330. self.logfile = logfile
  331. # input from child (read_nonblocking)
  332. self.logfile_read = None
  333. # output to send (send, sendline)
  334. self.logfile_send = None
  335. # max bytes to read at one time into buffer
  336. self.maxread = maxread
  337. # This is the read buffer. See maxread.
  338. self.buffer = ''
  339. # Data before searchwindowsize point is preserved, but not searched.
  340. self.searchwindowsize = searchwindowsize
  341. # Delay used before sending data to child. Time in seconds.
  342. # Most Linux machines don't like this to be below 0.03 (30 ms).
  343. self.delaybeforesend = 0.05
  344. # Used by close() to give kernel time to update process status.
  345. # Time in seconds.
  346. self.delayafterclose = 0.1
  347. # Used by terminate() to give kernel time to update process status.
  348. # Time in seconds.
  349. self.delayafterterminate = 0.1
  350. self.softspace = False
  351. self.name = '<' + repr(self) + '>'
  352. self.encoding = None
  353. self.closed = True
  354. self.cwd = cwd
  355. self.env = env
  356. # This flags if we are running on irix
  357. self.__irix_hack = (sys.platform.lower().find('irix') >= 0)
  358. # Solaris uses internal __fork_pty(). All others use pty.fork().
  359. if ((sys.platform.lower().find('solaris') >= 0)
  360. or (sys.platform.lower().find('sunos5') >= 0)):
  361. self.use_native_pty_fork = False
  362. else:
  363. self.use_native_pty_fork = True
  364. # Support subclasses that do not use command or args.
  365. if command is None:
  366. self.command = None
  367. self.args = None
  368. self.name = '<pexpect factory incomplete>'
  369. else:
  370. self._spawn(command, args)
  371. def __del__(self):
  372. """This makes sure that no system resources are left open. Python only
  373. garbage collects Python objects. OS file descriptors are not Python
  374. objects, so they must be handled explicitly. If the child file
  375. descriptor was opened outside of this class (passed to the constructor)
  376. then this does not close it. """
  377. if not self.closed:
  378. # It is possible for __del__ methods to execute during the
  379. # teardown of the Python VM itself. Thus self.close() may
  380. # trigger an exception because os.close may be None.
  381. # -- Fernando Perez
  382. try:
  383. self.close()
  384. except:
  385. pass
  386. def __str__(self):
  387. """This returns a human-readable string that represents the state of
  388. the object. """
  389. s = []
  390. s.append(repr(self))
  391. s.append('version: ' + __version__ + ' (' + __revision__ + ')')
  392. s.append('command: ' + str(self.command))
  393. s.append('args: ' + str(self.args))
  394. s.append('searcher: ' + str(self.searcher))
  395. s.append('buffer (last 100 chars): ' + str(self.buffer)[-100:])
  396. s.append('before (last 100 chars): ' + str(self.before)[-100:])
  397. s.append('after: ' + str(self.after))
  398. s.append('match: ' + str(self.match))
  399. s.append('match_index: ' + str(self.match_index))
  400. s.append('exitstatus: ' + str(self.exitstatus))
  401. s.append('flag_eof: ' + str(self.flag_eof))
  402. s.append('pid: ' + str(self.pid))
  403. s.append('child_fd: ' + str(self.child_fd))
  404. s.append('closed: ' + str(self.closed))
  405. s.append('timeout: ' + str(self.timeout))
  406. s.append('delimiter: ' + str(self.delimiter))
  407. s.append('logfile: ' + str(self.logfile))
  408. s.append('logfile_read: ' + str(self.logfile_read))
  409. s.append('logfile_send: ' + str(self.logfile_send))
  410. s.append('maxread: ' + str(self.maxread))
  411. s.append('ignorecase: ' + str(self.ignorecase))
  412. s.append('searchwindowsize: ' + str(self.searchwindowsize))
  413. s.append('delaybeforesend: ' + str(self.delaybeforesend))
  414. s.append('delayafterclose: ' + str(self.delayafterclose))
  415. s.append('delayafterterminate: ' + str(self.delayafterterminate))
  416. return '\n'.join(s)
  417. def _spawn(self, command, args=[]):
  418. """This starts the given command in a child process. This does all the
  419. fork/exec type of stuff for a pty. This is called by __init__. If args
  420. is empty then command will be parsed (split on spaces) and args will be
  421. set to parsed arguments. """
  422. # The pid and child_fd of this object get set by this method.
  423. # Note that it is difficult for this method to fail.
  424. # You cannot detect if the child process cannot start.
  425. # So the only way you can tell if the child process started
  426. # or not is to try to read from the file descriptor. If you get
  427. # EOF immediately then it means that the child is already dead.
  428. # That may not necessarily be bad because you may have spawned a child
  429. # that performs some task; creates no stdout output; and then dies.
  430. # If command is an int type then it may represent a file descriptor.
  431. if isinstance(command, type(0)):
  432. raise ExceptionPexpect('Command is an int type. ' +
  433. 'If this is a file descriptor then maybe you want to ' +
  434. 'use fdpexpect.fdspawn which takes an existing ' +
  435. 'file descriptor instead of a command string.')
  436. if not isinstance(args, type([])):
  437. raise TypeError('The argument, args, must be a list.')
  438. if args == []:
  439. self.args = split_command_line(command)
  440. self.command = self.args[0]
  441. else:
  442. # Make a shallow copy of the args list.
  443. self.args = args[:]
  444. self.args.insert(0, command)
  445. self.command = command
  446. command_with_path = which(self.command)
  447. if command_with_path is None:
  448. raise ExceptionPexpect('The command was not found or was not ' +
  449. 'executable: %s.' % self.command)
  450. self.command = command_with_path
  451. self.args[0] = self.command
  452. self.name = '<' + ' '.join(self.args) + '>'
  453. assert self.pid is None, 'The pid member must be None.'
  454. assert self.command is not None, 'The command member must not be None.'
  455. if self.use_native_pty_fork:
  456. try:
  457. self.pid, self.child_fd = pty.fork()
  458. except OSError as e:
  459. raise ExceptionPexpect('pty.fork() failed: ' + str(e))
  460. else:
  461. # Use internal __fork_pty
  462. self.pid, self.child_fd = self.__fork_pty()
  463. if self.pid == 0:
  464. # Child
  465. try:
  466. # used by setwinsize()
  467. self.child_fd = sys.stdout.fileno()
  468. self.setwinsize(24, 80)
  469. except:
  470. # Some platforms do not like setwinsize (Cygwin).
  471. # This will cause problem when running applications that
  472. # are very picky about window size.
  473. # This is a serious limitation, but not a show stopper.
  474. pass
  475. # Do not allow child to inherit open file descriptors from parent.
  476. max_fd = resource.getrlimit(resource.RLIMIT_NOFILE)[0]
  477. for i in range(3, max_fd):
  478. try:
  479. os.close(i)
  480. except OSError:
  481. pass
  482. # I don't know why this works, but ignoring SIGHUP fixes a
  483. # problem when trying to start a Java daemon with sudo
  484. # (specifically, Tomcat).
  485. signal.signal(signal.SIGHUP, signal.SIG_IGN)
  486. if self.cwd is not None:
  487. os.chdir(self.cwd)
  488. if self.env is None:
  489. os.execv(self.command, self.args)
  490. else:
  491. os.execvpe(self.command, self.args, self.env)
  492. # Parent
  493. self.terminated = False
  494. self.closed = False
  495. def __fork_pty(self):
  496. """This implements a substitute for the forkpty system call. This
  497. should be more portable than the pty.fork() function. Specifically,
  498. this should work on Solaris.
  499. Modified 10.06.05 by Geoff Marshall: Implemented __fork_pty() method to
  500. resolve the issue with Python's pty.fork() not supporting Solaris,
  501. particularly ssh. Based on patch to posixmodule.c authored by Noah
  502. Spurrier::
  503. http://mail.python.org/pipermail/python-dev/2003-May/035281.html
  504. """
  505. parent_fd, child_fd = os.openpty()
  506. if parent_fd < 0 or child_fd < 0:
  507. raise ExceptionPexpect("Could not open with os.openpty().")
  508. pid = os.fork()
  509. if pid < 0:
  510. raise ExceptionPexpect("Failed os.fork().")
  511. elif pid == 0:
  512. # Child.
  513. os.close(parent_fd)
  514. self.__pty_make_controlling_tty(child_fd)
  515. os.dup2(child_fd, 0)
  516. os.dup2(child_fd, 1)
  517. os.dup2(child_fd, 2)
  518. if child_fd > 2:
  519. os.close(child_fd)
  520. else:
  521. # Parent.
  522. os.close(child_fd)
  523. return pid, parent_fd
  524. def __pty_make_controlling_tty(self, tty_fd):
  525. """This makes the pseudo-terminal the controlling tty. This should be
  526. more portable than the pty.fork() function. Specifically, this should
  527. work on Solaris. """
  528. child_name = os.ttyname(tty_fd)
  529. # Disconnect from controlling tty. Harmless if not already connected.
  530. try:
  531. fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
  532. if fd >= 0:
  533. os.close(fd)
  534. except:
  535. # Already disconnected. This happens if running inside cron.
  536. pass
  537. os.setsid()
  538. # Verify we are disconnected from controlling tty
  539. # by attempting to open it again.
  540. try:
  541. fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
  542. if fd >= 0:
  543. os.close(fd)
  544. raise ExceptionPexpect('Failed to disconnect from ' +
  545. 'controlling tty. It is still possible to open /dev/tty.')
  546. except:
  547. # Good! We are disconnected from a controlling tty.
  548. pass
  549. # Verify we can open child pty.
  550. fd = os.open(child_name, os.O_RDWR)
  551. if fd < 0:
  552. raise ExceptionPexpect("Could not open child pty, " + child_name)
  553. else:
  554. os.close(fd)
  555. # Verify we now have a controlling tty.
  556. fd = os.open("/dev/tty", os.O_WRONLY)
  557. if fd < 0:
  558. raise ExceptionPexpect("Could not open controlling tty, /dev/tty")
  559. else:
  560. os.close(fd)
  561. def fileno(self):
  562. """This returns the file descriptor of the pty for the child.
  563. """
  564. return self.child_fd
  565. def close(self, force=True):
  566. """This closes the connection with the child application. Note that
  567. calling close() more than once is valid. This emulates standard Python
  568. behavior with files. Set force to True if you want to make sure that
  569. the child is terminated (SIGKILL is sent if the child ignores SIGHUP
  570. and SIGINT). """
  571. if not self.closed:
  572. self.flush()
  573. os.close(self.child_fd)
  574. # Give kernel time to update process status.
  575. time.sleep(self.delayafterclose)
  576. if self.isalive():
  577. if not self.terminate(force):
  578. raise ExceptionPexpect('Could not terminate the child.')
  579. self.child_fd = -1
  580. self.closed = True
  581. #self.pid = None
  582. def flush(self):
  583. """This does nothing. It is here to support the interface for a
  584. File-like object. """
  585. pass
  586. def isatty(self):
  587. """This returns True if the file descriptor is open and connected to a
  588. tty(-like) device, else False. """
  589. return os.isatty(self.child_fd)
  590. def waitnoecho(self, timeout=-1):
  591. """This waits until the terminal ECHO flag is set False. This returns
  592. True if the echo mode is off. This returns False if the ECHO flag was
  593. not set False before the timeout. This can be used to detect when the
  594. child is waiting for a password. Usually a child application will turn
  595. off echo mode when it is waiting for the user to enter a password. For
  596. example, instead of expecting the "password:" prompt you can wait for
  597. the child to set ECHO off::
  598. p = pexpect.spawn('ssh user@example.com')
  599. p.waitnoecho()
  600. p.sendline(mypassword)
  601. If timeout==-1 then this method will use the value in self.timeout.
  602. If timeout==None then this method to block until ECHO flag is False.
  603. """
  604. if timeout == -1:
  605. timeout = self.timeout
  606. if timeout is not None:
  607. end_time = time.time() + timeout
  608. while True:
  609. if not self.getecho():
  610. return True
  611. if timeout < 0 and timeout is not None:
  612. return False
  613. if timeout is not None:
  614. timeout = end_time - time.time()
  615. time.sleep(0.1)
  616. def getecho(self):
  617. """This returns the terminal echo mode. This returns True if echo is
  618. on or False if echo is off. Child applications that are expecting you
  619. to enter a password often set ECHO False. See waitnoecho(). """
  620. attr = termios.tcgetattr(self.child_fd)
  621. if attr[3] & termios.ECHO:
  622. return True
  623. return False
  624. def setecho(self, state):
  625. """This sets the terminal echo mode on or off. Note that anything the
  626. child sent before the echo will be lost, so you should be sure that
  627. your input buffer is empty before you call setecho(). For example, the
  628. following will work as expected::
  629. p = pexpect.spawn('cat') # Echo is on by default.
  630. p.sendline('1234') # We expect see this twice from the child...
  631. p.expect(['1234']) # ... once from the tty echo...
  632. p.expect(['1234']) # ... and again from cat itself.
  633. p.setecho(False) # Turn off tty echo
  634. p.sendline('abcd') # We will set this only once (echoed by cat).
  635. p.sendline('wxyz') # We will set this only once (echoed by cat)
  636. p.expect(['abcd'])
  637. p.expect(['wxyz'])
  638. The following WILL NOT WORK because the lines sent before the setecho
  639. will be lost::
  640. p = pexpect.spawn('cat')
  641. p.sendline('1234')
  642. p.setecho(False) # Turn off tty echo
  643. p.sendline('abcd') # We will set this only once (echoed by cat).
  644. p.sendline('wxyz') # We will set this only once (echoed by cat)
  645. p.expect(['1234'])
  646. p.expect(['1234'])
  647. p.expect(['abcd'])
  648. p.expect(['wxyz'])
  649. """
  650. self.child_fd
  651. attr = termios.tcgetattr(self.child_fd)
  652. if state:
  653. attr[3] = attr[3] | termios.ECHO
  654. else:
  655. attr[3] = attr[3] & ~termios.ECHO
  656. # I tried TCSADRAIN and TCSAFLUSH, but
  657. # these were inconsistent and blocked on some platforms.
  658. # TCSADRAIN would probably be ideal if it worked.
  659. termios.tcsetattr(self.child_fd, termios.TCSANOW, attr)
  660. def read_nonblocking(self, size=1, timeout=-1):
  661. """This reads at most size characters from the child application. It
  662. includes a timeout. If the read does not complete within the timeout
  663. period then a TIMEOUT exception is raised. If the end of file is read
  664. then an EOF exception will be raised. If a log file was set using
  665. setlog() then all data will also be written to the log file.
  666. If timeout is None then the read may block indefinitely.
  667. If timeout is -1 then the self.timeout value is used. If timeout is 0
  668. then the child is polled and if there is no data immediately ready
  669. then this will raise a TIMEOUT exception.
  670. The timeout refers only to the amount of time to read at least one
  671. character. This is not effected by the 'size' parameter, so if you call
  672. read_nonblocking(size=100, timeout=30) and only one character is
  673. available right away then one character will be returned immediately.
  674. It will not wait for 30 seconds for another 99 characters to come in.
  675. This is a wrapper around os.read(). It uses select.select() to
  676. implement the timeout. """
  677. if self.closed:
  678. raise ValueError('I/O operation on closed file.')
  679. if timeout == -1:
  680. timeout = self.timeout
  681. # Note that some systems such as Solaris do not give an EOF when
  682. # the child dies. In fact, you can still try to read
  683. # from the child_fd -- it will block forever or until TIMEOUT.
  684. # For this case, I test isalive() before doing any reading.
  685. # If isalive() is false, then I pretend that this is the same as EOF.
  686. if not self.isalive():
  687. # timeout of 0 means "poll"
  688. r, w, e = self.__select([self.child_fd], [], [], 0)
  689. if not r:
  690. self.flag_eof = True
  691. raise EOF('End Of File (EOF). Braindead platform.')
  692. elif self.__irix_hack:
  693. # Irix takes a long time before it realizes a child was terminated.
  694. # FIXME So does this mean Irix systems are forced to always have
  695. # FIXME a 2 second delay when calling read_nonblocking? That sucks.
  696. r, w, e = self.__select([self.child_fd], [], [], 2)
  697. if not r and not self.isalive():
  698. self.flag_eof = True
  699. raise EOF('End Of File (EOF). Slow platform.')
  700. r, w, e = self.__select([self.child_fd], [], [], timeout)
  701. if not r:
  702. if not self.isalive():
  703. # Some platforms, such as Irix, will claim that their
  704. # processes are alive; timeout on the select; and
  705. # then finally admit that they are not alive.
  706. self.flag_eof = True
  707. raise EOF('End of File (EOF). Very slow platform.')
  708. else:
  709. raise TIMEOUT('Timeout exceeded.')
  710. if self.child_fd in r:
  711. try:
  712. s = os.read(self.child_fd, size)
  713. except OSError as e:
  714. # Linux does this
  715. self.flag_eof = True
  716. raise EOF('End Of File (EOF). Exception style platform.')
  717. if s == '':
  718. # BSD style
  719. self.flag_eof = True
  720. raise EOF('End Of File (EOF). Empty string style platform.')
  721. if self.logfile is not None:
  722. self.logfile.write(s)
  723. self.logfile.flush()
  724. if self.logfile_read is not None:
  725. self.logfile_read.write(s)
  726. self.logfile_read.flush()
  727. return s
  728. raise ExceptionPexpect('Reached an unexpected state.')
  729. def read(self, size=-1):
  730. """This reads at most "size" bytes from the file (less if the read hits
  731. EOF before obtaining size bytes). If the size argument is negative or
  732. omitted, read all data until EOF is reached. The bytes are returned as
  733. a string object. An empty string is returned when EOF is encountered
  734. immediately. """
  735. if size == 0:
  736. return ''
  737. if size < 0:
  738. # delimiter default is EOF
  739. self.expect(self.delimiter)
  740. return self.before
  741. # I could have done this more directly by not using expect(), but
  742. # I deliberately decided to couple read() to expect() so that
  743. # I would catch any bugs early and ensure consistant behavior.
  744. # It's a little less efficient, but there is less for me to
  745. # worry about if I have to later modify read() or expect().
  746. # Note, it's OK if size==-1 in the regex. That just means it
  747. # will never match anything in which case we stop only on EOF.
  748. cre = re.compile('.{%d}' % size, re.DOTALL)
  749. # delimiter default is EOF
  750. index = self.expect([cre, self.delimiter])
  751. if index == 0:
  752. ### FIXME self.before should be ''. Should I assert this?
  753. return self.after
  754. return self.before
  755. def readline(self, size=-1):
  756. """This reads and returns one entire line. The newline at the end of
  757. line is returned as part of the string, unless the file ends without a
  758. newline. An empty string is returned if EOF is encountered immediately.
  759. This looks for a newline as a CR/LF pair (\\r\\n) even on UNIX because
  760. this is what the pseudotty device returns. So contrary to what you may
  761. expect you will receive newlines as \\r\\n.
  762. If the size argument is 0 then an empty string is returned. In all
  763. other cases the size argument is ignored, which is not standard
  764. behavior for a file-like object. """
  765. if size == 0:
  766. return ''
  767. # delimiter default is EOF
  768. index = self.expect(['\r\n', self.delimiter])
  769. if index == 0:
  770. return self.before + '\r\n'
  771. else:
  772. return self.before
  773. def __iter__(self):
  774. """This is to support iterators over a file-like object.
  775. """
  776. return self
  777. def __next__(self):
  778. """This is to support iterators over a file-like object.
  779. """
  780. result = self.readline()
  781. if result == "":
  782. raise StopIteration
  783. return result
  784. def readlines(self, sizehint=-1):
  785. """This reads until EOF using readline() and returns a list containing
  786. the lines thus read. The optional 'sizehint' argument is ignored. """
  787. lines = []
  788. while True:
  789. line = self.readline()
  790. if not line:
  791. break
  792. lines.append(line)
  793. return lines
  794. def write(self, s):
  795. """This is similar to send() except that there is no return value.
  796. """
  797. self.send(s)
  798. def writelines(self, sequence):
  799. """This calls write() for each element in the sequence. The sequence
  800. can be any iterable object producing strings, typically a list of
  801. strings. This does not add line separators There is no return value.
  802. """
  803. for s in sequence:
  804. self.write(s)
  805. def send(self, s):
  806. """This sends a string to the child process. This returns the number of
  807. bytes written. If a log file was set then the data is also written to
  808. the log. """
  809. time.sleep(self.delaybeforesend)
  810. if self.logfile is not None:
  811. self.logfile.write(s)
  812. self.logfile.flush()
  813. if self.logfile_send is not None:
  814. self.logfile_send.write(s)
  815. self.logfile_send.flush()
  816. c = os.write(self.child_fd, s.encode("utf-8"))
  817. return c
  818. def sendline(self, s=''):
  819. """This is like send(), but it adds a linefeed (os.linesep). This
  820. returns the number of bytes written. """
  821. n = self.send(s)
  822. n = n + self.send(os.linesep)
  823. return n
  824. def sendcontrol(self, char):
  825. """This sends a control character to the child such as Ctrl-C or
  826. Ctrl-D. For example, to send a Ctrl-G (ASCII 7)::
  827. child.sendcontrol('g')
  828. See also, sendintr() and sendeof().
  829. """
  830. char = char.lower()
  831. a = ord(char)
  832. if a >= 97 and a <= 122:
  833. a = a - ord('a') + 1
  834. return self.send(chr(a))
  835. d = {'@': 0, '`': 0,
  836. '[': 27, '{': 27,
  837. '\\': 28, '|': 28,
  838. ']': 29, '}': 29,
  839. '^': 30, '~': 30,
  840. '_': 31,
  841. '?': 127}
  842. if char not in d:
  843. return 0
  844. return self.send(chr(d[char]))
  845. def sendeof(self):
  846. """This sends an EOF to the child. This sends a character which causes
  847. the pending parent output buffer to be sent to the waiting child
  848. program without waiting for end-of-line. If it is the first character
  849. of the line, the read() in the user program returns 0, which signifies
  850. end-of-file. This means to work as expected a sendeof() has to be
  851. called at the beginning of a line. This method does not send a newline.
  852. It is the responsibility of the caller to ensure the eof is sent at the
  853. beginning of a line. """
  854. ### Hmmm... how do I send an EOF?
  855. ###C if ((m = write(pty, *buf, p - *buf)) < 0)
  856. ###C return (errno == EWOULDBLOCK) ? n : -1;
  857. #fd = sys.stdin.fileno()
  858. #old = termios.tcgetattr(fd) # remember current state
  859. #attr = termios.tcgetattr(fd)
  860. #attr[3] = attr[3] | termios.ICANON # ICANON must be set to see EOF
  861. #try: # use try/finally to ensure state gets restored
  862. # termios.tcsetattr(fd, termios.TCSADRAIN, attr)
  863. # if hasattr(termios, 'CEOF'):
  864. # os.write(self.child_fd, '%c' % termios.CEOF)
  865. # else:
  866. # # Silly platform does not define CEOF so assume CTRL-D
  867. # os.write(self.child_fd, '%c' % 4)
  868. #finally: # restore state
  869. # termios.tcsetattr(fd, termios.TCSADRAIN, old)
  870. if hasattr(termios, 'VEOF'):
  871. char = termios.tcgetattr(self.child_fd)[6][termios.VEOF]
  872. else:
  873. # platform does not define VEOF so assume CTRL-D
  874. char = chr(4)
  875. self.send(char)
  876. def sendintr(self):
  877. """This sends a SIGINT to the child. It does not require
  878. the SIGINT to be the first character on a line. """
  879. if hasattr(termios, 'VINTR'):
  880. char = termios.tcgetattr(self.child_fd)[6][termios.VINTR]
  881. else:
  882. # platform does not define VINTR so assume CTRL-C
  883. char = chr(3)
  884. self.send(char)
  885. def eof(self):
  886. """This returns True if the EOF exception was ever raised.
  887. """
  888. return self.flag_eof
  889. def terminate(self, force=False):
  890. """This forces a child process to terminate. It starts nicely with
  891. SIGHUP and SIGINT. If "force" is True then moves onto SIGKILL. This
  892. returns True if the child was terminated. This returns False if the
  893. child could not be terminated. """
  894. if not self.isalive():
  895. return True
  896. try:
  897. self.kill(signal.SIGHUP)
  898. time.sleep(self.delayafterterminate)
  899. if not self.isalive():
  900. return True
  901. self.kill(signal.SIGCONT)
  902. time.sleep(self.delayafterterminate)
  903. if not self.isalive():
  904. return True
  905. self.kill(signal.SIGINT)
  906. time.sleep(self.delayafterterminate)
  907. if not self.isalive():
  908. return True
  909. if force:
  910. self.kill(signal.SIGKILL)
  911. time.sleep(self.delayafterterminate)
  912. if not self.isalive():
  913. return True
  914. else:
  915. return False
  916. return False
  917. except OSError as e:
  918. # I think there are kernel timing issues that sometimes cause
  919. # this to happen. I think isalive() reports True, but the
  920. # process is dead to the kernel.
  921. # Make one last attempt to see if the kernel is up to date.
  922. time.sleep(self.delayafterterminate)
  923. if not self.isalive():
  924. return True
  925. else:
  926. return False
  927. def wait(self):
  928. """This waits until the child exits. This is a blocking call. This will
  929. not read any data from the child, so this will block forever if the
  930. child has unread output and has terminated. In other words, the child
  931. may have printed output then called exit(), but, the child is
  932. technically still alive until its output is read by the parent. """
  933. if self.isalive():
  934. pid, status = os.waitpid(self.pid, 0)
  935. else:
  936. raise ExceptionPexpect('Cannot wait for dead child process.')
  937. self.exitstatus = os.WEXITSTATUS(status)
  938. if os.WIFEXITED(status):
  939. self.status = status
  940. self.exitstatus = os.WEXITSTATUS(status)
  941. self.signalstatus = None
  942. self.terminated = True
  943. elif os.WIFSIGNALED(status):
  944. self.status = status
  945. self.exitstatus = None
  946. self.signalstatus = os.WTERMSIG(status)
  947. self.terminated = True
  948. elif os.WIFSTOPPED(status):
  949. # You can't call wait() on a child process in the stopped state.
  950. raise ExceptionPexpect('Called wait() on a stopped child ' +
  951. 'process. This is not supported. Is some other ' +
  952. 'process attempting job control with our child pid?')
  953. return self.exitstatus
  954. def isalive(self):
  955. """This tests if the child process is running or not. This is
  956. non-blocking. If the child was terminated then this will read the
  957. exitstatus or signalstatus of the child. This returns True if the child
  958. process appears to be running or False if not. It can take literally
  959. SECONDS for Solaris to return the right status. """
  960. if self.terminated:
  961. return False
  962. if self.flag_eof:
  963. # This is for Linux, which requires the blocking form
  964. # of waitpid to # get status of a defunct process.
  965. # This is super-lame. The flag_eof would have been set
  966. # in read_nonblocking(), so this should be safe.
  967. waitpid_options = 0
  968. else:
  969. waitpid_options = os.WNOHANG
  970. try:
  971. pid, status = os.waitpid(self.pid, waitpid_options)
  972. except OSError as e:
  973. # No child processes
  974. if e[0] == errno.ECHILD:
  975. raise ExceptionPexpect('isalive() encountered condition ' +
  976. 'where "terminated" is 0, but there was no child ' +
  977. 'process. Did someone else call waitpid() ' +
  978. 'on our process?')
  979. else:
  980. raise e
  981. # I have to do this twice for Solaris.
  982. # I can't even believe that I figured this out...
  983. # If waitpid() returns 0 it means that no child process
  984. # wishes to report, and the value of status is undefined.
  985. if pid == 0:
  986. try:
  987. ### os.WNOHANG) # Solaris!
  988. pid, status = os.waitpid(self.pid, waitpid_options)
  989. except OSError as e:
  990. # This should never happen...
  991. if e[0] == errno.ECHILD:
  992. raise ExceptionPexpect('isalive() encountered condition ' +
  993. 'that should never happen. There was no child ' +
  994. 'process. Did someone else call waitpid() ' +
  995. 'on our process?')
  996. else:
  997. raise e
  998. # If pid is still 0 after two calls to waitpid() then the process
  999. # really is alive. This seems to work on all platforms, except for
  1000. # Irix which seems to require a blocking call on waitpid or select,
  1001. # so I let read_nonblocking take care of this situation
  1002. # (unfortunately, this requires waiting through the timeout).
  1003. if pid == 0:
  1004. return True
  1005. if pid == 0:
  1006. return True
  1007. if os.WIFEXITED(status):
  1008. self.status = status
  1009. self.exitstatus = os.WEXITSTATUS(status)
  1010. self.signalstatus = None
  1011. self.terminated = True
  1012. elif os.WIFSIGNALED(status):
  1013. self.status = status
  1014. self.exitstatus = None
  1015. self.signalstatus = os.WTERMSIG(status)
  1016. self.terminated = True
  1017. elif os.WIFSTOPPED(status):
  1018. raise ExceptionPexpect('isalive() encountered condition ' +
  1019. 'where child process is stopped. This is not ' +
  1020. 'supported. Is some other process attempting ' +
  1021. 'job control with our child pid?')
  1022. return False
  1023. def kill(self, sig):
  1024. """This sends the given signal to the child application. In keeping
  1025. with UNIX tradition it has a misleading name. It does not necessarily
  1026. kill the child unless you send the right signal. """
  1027. # Same as os.kill, but the pid is given for you.
  1028. if self.isalive():
  1029. os.kill(self.pid, sig)
  1030. def compile_pattern_list(self, patterns):
  1031. """This compiles a pattern-string or a list of pattern-strings.
  1032. Patterns must be a StringType, EOF, TIMEOUT, SRE_Pattern, or a list of
  1033. those. Patterns may also be None which results in an empty list (you
  1034. might do this if waiting for an EOF or TIMEOUT condition without
  1035. expecting any pattern).
  1036. This is used by expect() when calling expect_list(). Thus expect() is
  1037. nothing more than::
  1038. cpl = self.compile_pattern_list(pl)
  1039. return self.expect_list(cpl, timeout)
  1040. If you are using expect() within a loop it may be more
  1041. efficient to compile the patterns first and then call expect_list().
  1042. This avoid calls in a loop to compile_pattern_list()::
  1043. cpl = self.compile_pattern_list(my_pattern)
  1044. while some_condition:
  1045. ...
  1046. i = self.expect_list(clp, timeout)
  1047. ...
  1048. """
  1049. if patterns is None:
  1050. return []
  1051. if not isinstance(patterns, list):
  1052. patterns = [patterns]
  1053. # Allow dot to match \n
  1054. compile_flags = re.DOTALL
  1055. if self.ignorecase:
  1056. compile_flags = compile_flags | re.IGNORECASE
  1057. compiled_pattern_list = []
  1058. for p in patterns:
  1059. if type(p) in types.StringTypes:
  1060. compiled_pattern_list.append(re.compile(p, compile_flags))
  1061. elif p is EOF:
  1062. compiled_pattern_list.append(EOF)
  1063. elif p is TIMEOUT:
  1064. compiled_pattern_list.append(TIMEOUT)
  1065. elif isinstance(p, type(re.compile(''))):
  1066. compiled_pattern_list.append(p)
  1067. else:
  1068. raise TypeError('Argument must be one of StringTypes, ' +
  1069. 'EOF, TIMEOUT, SRE_Pattern, or a list of those ' +
  1070. 'type. %s' % str(type(p)))
  1071. return compiled_pattern_list
  1072. def expect(self, pattern, timeout=-1, searchwindowsize=-1):
  1073. """This seeks through the stream until a pattern is matched. The
  1074. pattern is overloaded and may take several types. The pattern can be a
  1075. StringType, EOF, a compiled re, or a list of any of those types.
  1076. Strings will be compiled to re types. This returns the index into the
  1077. pattern list. If the pattern was not a list this returns index 0 on a
  1078. successful match. This may raise exceptions for EOF or TIMEOUT. To
  1079. avoid the EOF or TIMEOUT exceptions add EOF or TIMEOUT to the pattern
  1080. list. That will cause expect to match an EOF or TIMEOUT condition
  1081. instead of raising an exception.
  1082. If you pass a list of patterns and more than one matches, the first
  1083. match in the stream is chosen. If more than one pattern matches at that
  1084. point, the leftmost in the pattern list is chosen. For example::
  1085. # the input is 'foobar'
  1086. index = p.expect(['bar', 'foo', 'foobar'])
  1087. # returns 1('foo') even though 'foobar' is a "better" match
  1088. Please note, however, that buffering can affect this behavior, since
  1089. input arrives in unpredictable chunks. For example::
  1090. # the input is 'foobar'
  1091. index = p.expect(['foobar', 'foo'])
  1092. # returns 0('foobar') if all input is available at once,
  1093. # but returs 1('foo') if parts of the final 'bar' arrive late
  1094. After a match is found the instance attributes 'before', 'after' and
  1095. 'match' will be set. You can see all the data read before the match in
  1096. 'before'. You can see the data that was matched in 'after'. The
  1097. re.MatchObject used in the re match will be in 'match'. If an error
  1098. occurred then 'before' will be set to all the data read so far and
  1099. 'after' and 'match' will be None.
  1100. If timeout is -1 then timeout will be set to the self.timeout value.
  1101. A list entry may be EOF or TIMEOUT instead of a string. This will
  1102. catch these exceptions and return the index of the list entry instead
  1103. of raising the exception. The attribute 'after' will be set to the
  1104. exception type. The attribute 'match' will be None. This allows you to
  1105. write code like this::
  1106. index = p.expect(['good', 'bad', pexpect.EOF, pexpect.TIMEOUT])
  1107. if index == 0:
  1108. do_something()
  1109. elif index == 1:
  1110. do_something_else()
  1111. elif index == 2:
  1112. do_some_other_thing()
  1113. elif index == 3:
  1114. do_something_completely_different()
  1115. instead of code like this::
  1116. try:
  1117. index = p.expect(['good', 'bad'])
  1118. if index == 0:
  1119. do_something()
  1120. elif index == 1:
  1121. do_something_else()
  1122. except EOF:
  1123. do_some_other_thing()
  1124. except TIMEOUT:
  1125. do_something_completely_different()
  1126. These two forms are equivalent. It all depends on what you want. You
  1127. can also just expect the EOF if you are waiting for all output of a
  1128. child to finish. For example::
  1129. p = pexpect.spawn('/bin/ls')
  1130. p.expect(pexpect.EOF)
  1131. print p.before
  1132. If you are trying to optimize for speed then see expect_list().
  1133. """
  1134. compiled_pattern_list = self.compile_pattern_list(pattern)
  1135. return self.expect_list(compiled_pattern_list,
  1136. timeout, searchwindowsize)
  1137. def expect_list(self, pattern_list, timeout=-1, searchwindowsize=-1):
  1138. """This takes a list of compiled regular expressions and returns the
  1139. index into the pattern_list that matched the child output. The list may
  1140. also contain EOF or TIMEOUT(which are not compiled regular
  1141. expressions). This method is similar to the expect() method except that
  1142. expect_list() does not recompile the pattern list on every call. This
  1143. may help if you are trying to optimize for speed, otherwise just use
  1144. the expect() method. This is called by expect(). If timeout==-1 then
  1145. the self.timeout value is used. If searchwindowsize==-1 then the
  1146. self.searchwindowsize value is used. """
  1147. return self.expect_loop(searcher_re(pattern_list),
  1148. timeout, searchwindowsize)
  1149. def expect_exact(self, pattern_list, timeout=-1, searchwindowsize=-1):
  1150. """This is similar to expect(), but uses plain string matching instead
  1151. of compiled regular expressions in 'pattern_list'. The 'pattern_list'
  1152. may be a string; a list or other sequence of strings; or TIMEOUT and
  1153. EOF.
  1154. This call might be faster than expect() for two reasons: string
  1155. searching is faster than RE matching and it is possible to limit the
  1156. search to just the end of the input buffer.
  1157. This method is also useful when you don't want to have to worry about
  1158. escaping regular expression characters that you want to match."""
  1159. if (type(pattern_list) in types.StringTypes or
  1160. pattern_list in (TIMEOUT, EOF)):
  1161. pattern_list = [pattern_list]
  1162. return self.expect_loop(searcher_string(pattern_list),
  1163. timeout, searchwindowsize)
  1164. def expect_loop(self, searcher, timeout=-1, searchwindowsize=-1):
  1165. """This is the common loop used inside expect. The 'searcher' should be
  1166. an instance of searcher_re or searcher_string, which describes how and
  1167. what to search for in the input.
  1168. See expect() for other arguments, return value and exceptions. """
  1169. self.searcher = searcher
  1170. if timeout == -1:
  1171. timeout = self.timeout
  1172. if timeout is not None:
  1173. end_time = time.time() + timeout
  1174. if searchwindowsize == -1:
  1175. searchwindowsize = self.searchwindowsize
  1176. try:
  1177. incoming = self.buffer
  1178. freshlen = len(incoming)
  1179. while True:
  1180. # Keep reading until exception or return.
  1181. index = searcher.search(incoming, freshlen, searchwindowsize)
  1182. if index >= 0:
  1183. self.buffer = incoming[searcher.end:]
  1184. self.before = incoming[: searcher.start]
  1185. self.after = incoming[searcher.start: searcher.end]
  1186. self.match = searcher.match
  1187. self.match_index = index
  1188. return self.match_index
  1189. # No match at this point
  1190. if timeout < 0 and timeout is not None:
  1191. raise TIMEOUT('Timeout exceeded in expect_any().')
  1192. # Still have time left, so read more data
  1193. c = self.read_nonblocking(self.maxread, timeout)
  1194. freshlen = len(c)
  1195. time.sleep(0.0001)
  1196. incoming = incoming + c
  1197. if timeout is not None:
  1198. timeout = end_time - time.time()
  1199. except EOF as e:
  1200. self.buffer = ''
  1201. self.before = incoming
  1202. self.after = EOF
  1203. index = searcher.eof_index
  1204. if index >= 0:
  1205. self.match = EOF
  1206. self.match_index = index
  1207. return self.match_index
  1208. else:
  1209. self.match = None
  1210. self.match_index = None
  1211. raise EOF(str(e) + '\n' + str(self))
  1212. except TIMEOUT as e:
  1213. self.buffer = incoming
  1214. self.before = incoming
  1215. self.after = TIMEOUT
  1216. index = searcher.timeout_index
  1217. if index >= 0:
  1218. self.match = TIMEOUT
  1219. self.match_index = index
  1220. return self.match_index
  1221. else:
  1222. self.match = None
  1223. self.match_index = None
  1224. raise TIMEOUT(str(e) + '\n' + str(self))
  1225. except:
  1226. self.before = incoming
  1227. self.after = None
  1228. self.match = None
  1229. self.match_index = None
  1230. raise
  1231. def getwinsize(self):
  1232. """This returns the terminal window size of the child tty. The return
  1233. value is a tuple of (rows, cols). """
  1234. TIOCGWINSZ = getattr(termios, 'TIOCGWINSZ', 1074295912)
  1235. s = struct.pack('HHHH', 0, 0, 0, 0)
  1236. x = fcntl.ioctl(self.fileno(), TIOCGWINSZ, s)
  1237. return struct.unpack('HHHH', x)[0:2]
  1238. def setwinsize(self, rows, cols):
  1239. """This sets the terminal window size of the child tty. This will cause
  1240. a SIGWINCH signal to be sent to the child. This does not change the
  1241. physical window size. It changes the size reported to TTY-aware
  1242. applications like vi or curses -- applications that respond to the
  1243. SIGWINCH signal. """
  1244. # Check for buggy platforms. Some Python versions on some platforms
  1245. # (notably OSF1 Alpha and RedHat 7.1) truncate the value for
  1246. # termios.TIOCSWINSZ. It is not clear why this happens.
  1247. # These platforms don't seem to handle the signed int very well;
  1248. # yet other platforms like OpenBSD have a large negative value for
  1249. # TIOCSWINSZ and they don't have a truncate problem.
  1250. # Newer versions of Linux have totally different values for TIOCSWINSZ.
  1251. # Note that this fix is a hack.
  1252. TIOCSWINSZ = getattr(termios, 'TIOCSWINSZ', -2146929561)
  1253. if TIOCSWINSZ == 2148037735:
  1254. # Same bits, but with sign.
  1255. TIOCSWINSZ = -2146929561
  1256. # Note, assume ws_xpixel and ws_ypixel are zero.
  1257. s = struct.pack('HHHH', rows, cols, 0, 0)
  1258. fcntl.ioctl(self.fileno(), TIOCSWINSZ, s)
  1259. def interact(self, escape_character=chr(29),
  1260. input_filter=None, output_filter=None):
  1261. """This gives control of the child process to the interactive user (the
  1262. human at the keyboard). Keystrokes are sent to the child process, and
  1263. the stdout and stderr output of the child process is printed. This
  1264. simply echos the child stdout and child stderr to the real stdout and
  1265. it echos the real stdin to the child stdin. When the user types the
  1266. escape_character this method will stop. The default for
  1267. escape_character is ^]. This should not be confused with ASCII 27 --
  1268. the ESC character. ASCII 29 was chosen for historical merit because
  1269. this is the character used by 'telnet' as the escape character. The
  1270. escape_character will not be sent to the child process.
  1271. You may pass in optional input and output filter functions. These
  1272. functions should take a string and return a string. The output_filter
  1273. will be passed all the output from the child process. The input_filter
  1274. will be passed all the keyboard input from the user. The input_filter
  1275. is run BEFORE the check for the escape_character.
  1276. Note that if you change the window size of the parent the SIGWINCH
  1277. signal will not be passed through to the child. If you want the child
  1278. window size to change when the parent's window size changes then do
  1279. something like the following example::
  1280. import pexpect, struct, fcntl, termios, signal, sys
  1281. def sigwinch_passthrough (sig, data):
  1282. s = struct.pack("HHHH", 0, 0, 0, 0)
  1283. a = struct.unpack('hhhh', fcntl.ioctl(sys.stdout.fileno(),
  1284. termios.TIOCGWINSZ , s))
  1285. global p
  1286. p.setwinsize(a[0],a[1])
  1287. # Note this 'p' global and used in sigwinch_passthrough.
  1288. p = pexpect.spawn('/bin/bash')
  1289. signal.signal(signal.SIGWINCH, sigwinch_passthrough)
  1290. p.interact()
  1291. """
  1292. # Flush the buffer.
  1293. self.stdout.write(self.buffer)
  1294. self.stdout.flush()
  1295. self.buffer = ''
  1296. mode = tty.tcgetattr(self.STDIN_FILENO)
  1297. tty.setraw(self.STDIN_FILENO)
  1298. try:
  1299. self.__interact_copy(escape_character, input_filter, output_filter)
  1300. finally:
  1301. tty.tcsetattr(self.STDIN_FILENO, tty.TCSAFLUSH, mode)
  1302. def __interact_writen(self, fd, data):
  1303. """This is used by the interact() method.
  1304. """
  1305. while data != '' and self.isalive():
  1306. n = os.write(fd, data)
  1307. data = data[n:]
  1308. def __interact_read(self, fd):
  1309. """This is used by the interact() method.
  1310. """
  1311. return os.read(fd, 1000)
  1312. def __interact_copy(self, escape_character=None,
  1313. input_filter=None, output_filter=None):
  1314. """This is used by the interact() method.
  1315. """
  1316. while self.isalive():
  1317. r, w, e = self.__select([self.child_fd, self.STDIN_FILENO], [], [])
  1318. if self.child_fd in r:
  1319. data = self.__interact_read(self.child_fd)
  1320. if output_filter:
  1321. data = output_filter(data)
  1322. if self.logfile is not None:
  1323. self.logfile.write(data)
  1324. self.logfile.flush()
  1325. os.write(self.STDOUT_FILENO, data)
  1326. if self.STDIN_FILENO in r:
  1327. data = self.__interact_read(self.STDIN_FILENO)
  1328. if input_filter:
  1329. data = input_filter(data)
  1330. i = data.rfind(escape_character)
  1331. if i != -1:
  1332. data = data[:i]
  1333. self.__interact_writen(self.child_fd, data)
  1334. break
  1335. self.__interact_writen(self.child_fd, data)
  1336. def __select(self, iwtd, owtd, ewtd, timeout=None):
  1337. """This is a wrapper around select.select() that ignores signals. If
  1338. select.select raises a select.error exception and errno is an EINTR
  1339. error then it is ignored. Mainly this is used to ignore sigwinch
  1340. (terminal resize). """
  1341. # if select() is interrupted by a signal (errno==EINTR) then
  1342. # we loop back and enter the select() again.
  1343. if timeout is not None:
  1344. end_time = time.time() + timeout
  1345. while True:
  1346. try:
  1347. return select.select(iwtd, owtd, ewtd, timeout)
  1348. except select.error as e:
  1349. if e[0] == errno.EINTR:
  1350. # if we loop back we have to subtract the
  1351. # amount of time we already waited.
  1352. if timeout is not None:
  1353. timeout = end_time - time.time()
  1354. if timeout < 0:
  1355. return([], [], [])
  1356. else:
  1357. # something else caused the select.error, so
  1358. # this actually is an exception.
  1359. raise
  1360. ##############################################################################
  1361. # The following methods are no longer supported or allowed.
  1362. def setmaxread(self, maxread):
  1363. """This method is no longer supported or allowed. I don't like getters
  1364. and setters without a good reason. """
  1365. raise ExceptionPexpect('This method is no longer supported ' +
  1366. 'or allowed. Just assign a value to the ' +
  1367. 'maxread member variable.')
  1368. def setlog(self, fileobject):
  1369. """This method is no longer supported or allowed.
  1370. """
  1371. raise ExceptionPexpect('This method is no longer supported ' +
  1372. 'or allowed. Just assign a value to the logfile ' +
  1373. 'member variable.')
  1374. ##############################################################################
  1375. # End of spawn class
  1376. ##############################################################################
  1377. class searcher_string(object):
  1378. """This is a plain string search helper for the spawn.expect_any() method.
  1379. This helper class is for speed. For more powerful regex patterns
  1380. see the helper class, searcher_re.
  1381. Attributes:
  1382. eof_index - index of EOF, or -1
  1383. timeout_index - index of TIMEOUT, or -1
  1384. After a successful match by the search() method the following attributes
  1385. are available:
  1386. start - index into the buffer, first byte of match
  1387. end - index into the buffer, first byte after match
  1388. match - the matching string itself
  1389. """
  1390. def __init__(self, strings):
  1391. """This creates an instance of searcher_string. This argument 'strings'
  1392. may be a list; a sequence of strings; or the EOF or TIMEOUT types. """
  1393. self.eof_index = -1
  1394. self.timeout_index = -1
  1395. self._strings = []
  1396. for n, s in zip(list(range(len(strings))), strings):
  1397. if s is EOF:
  1398. self.eof_index = n
  1399. continue
  1400. if s is TIMEOUT:
  1401. self.timeout_index = n
  1402. continue
  1403. self._strings.append((n, s))
  1404. def __str__(self):
  1405. """This returns a human-readable string that represents the state of
  1406. the object."""
  1407. ss = [(ns[0], ' %d: "%s"' % ns) for ns in self._strings]
  1408. ss.append((-1, 'searcher_string:'))
  1409. if self.eof_index >= 0:
  1410. ss.append((self.eof_index, ' %d: EOF' % self.eof_index))
  1411. if self.timeout_index >= 0:
  1412. ss.append((self.timeout_index,
  1413. ' %d: TIMEOUT' % self.timeout_index))
  1414. ss.sort()
  1415. ss = zip(*ss)[1]
  1416. return '\n'.join(ss)
  1417. def search(self, buffer, freshlen, searchwindowsize=None):
  1418. """This searches 'buffer' for the first occurence of one of the search
  1419. strings. 'freshlen' must indicate the number of bytes at the end of
  1420. 'buffer' which have not been searched before. It helps to avoid
  1421. searching the same, possibly big, buffer over and over again.
  1422. See class spawn for the 'searchwindowsize' argument.
  1423. If there is a match this returns the index of that string, and sets
  1424. 'start', 'end' and 'match'. Otherwise, this returns -1. """
  1425. absurd_match = len(buffer)
  1426. first_match = absurd_match
  1427. # 'freshlen' helps a lot here. Further optimizations could
  1428. # possibly include:
  1429. #
  1430. # using something like the Boyer-Moore Fast String Searching
  1431. # Algorithm; pre-compiling the search through a list of
  1432. # strings into something that can scan the input once to
  1433. # search for all N strings; realize that if we search for
  1434. # ['bar', 'baz'] and the input is '...foo' we need not bother
  1435. # rescanning until we've read three more bytes.
  1436. #
  1437. # Sadly, I don't know enough about this interesting topic. /grahn
  1438. for index, s in self._strings:
  1439. if searchwindowsize is None:
  1440. # the match, if any, can only be in the fresh data,
  1441. # or at the very end of the old data
  1442. offset = -(freshlen + len(s))
  1443. else:
  1444. # better obey searchwindowsize
  1445. offset = -searchwindowsize
  1446. n = buffer.find(s, offset)
  1447. if n >= 0 and n < first_match:
  1448. first_match = n
  1449. best_index, best_match = index, s
  1450. if first_match == absurd_match:
  1451. return -1
  1452. self.match = best_match
  1453. self.start = first_match
  1454. self.end = self.start + len(self.match)
  1455. return best_index
  1456. class searcher_re(object):
  1457. """This is regular expression string search helper for the
  1458. spawn.expect_any() method. This helper class is for powerful
  1459. pattern matching. For speed, see the helper class, searcher_string.
  1460. Attributes:
  1461. eof_index - index of EOF, or -1
  1462. timeout_index - index of TIMEOUT, or -1
  1463. After a successful match by the search() method the following attributes
  1464. are available:
  1465. start - index into the buffer, first byte of match
  1466. end - index into the buffer, first byte after match
  1467. match - the re.match object returned by a succesful re.search
  1468. """
  1469. def __init__(self, patterns):
  1470. """This creates an instance that searches for 'patterns' Where
  1471. 'patterns' may be a list or other sequence of compiled regular
  1472. expressions, or the EOF or TIMEOUT types."""
  1473. self.eof_index = -1
  1474. self.timeout_index = -1
  1475. self._searches = []
  1476. for n, s in zip(list(range(len(patterns))), patterns):
  1477. if s is EOF:
  1478. self.eof_index = n
  1479. continue
  1480. if s is TIMEOUT:
  1481. self.timeout_index = n
  1482. continue
  1483. self._searches.append((n, s))
  1484. def __str__(self):
  1485. """This returns a human-readable string that represents the state of
  1486. the object."""
  1487. ss = [(n, ' %d: re.compile("%s")' %
  1488. (n, str(s.pattern))) for n, s in self._searches]
  1489. ss.append((-1, 'searcher_re:'))
  1490. if self.eof_index >= 0:
  1491. ss.append((self.eof_index, ' %d: EOF' % self.eof_index))
  1492. if self.timeout_index >= 0:
  1493. ss.append((self.timeout_index, ' %d: TIMEOUT' %
  1494. self.timeout_index))
  1495. ss.sort()
  1496. ss = zip(*ss)[1]
  1497. return '\n'.join(ss)
  1498. def search(self, buffer, freshlen, searchwindowsize=None):
  1499. """This searches 'buffer' for the first occurence of one of the regular
  1500. expressions. 'freshlen' must indicate the number of bytes at the end of
  1501. 'buffer' which have not been searched before.
  1502. See class spawn for the 'searchwindowsize' argument.
  1503. If there is a match this returns the index of that string, and sets
  1504. 'start', 'end' and 'match'. Otherwise, returns -1."""
  1505. absurd_match = len(buffer)
  1506. first_match = absurd_match
  1507. # 'freshlen' doesn't help here -- we cannot predict the
  1508. # length of a match, and the re module provides no help.
  1509. if searchwindowsize is None:
  1510. searchstart = 0
  1511. else:
  1512. searchstart = max(0, len(buffer) - searchwindowsize)
  1513. for index, s in self._searches:
  1514. match = s.search(buffer, searchstart)
  1515. if match is None:
  1516. continue
  1517. n = match.start()
  1518. if n < first_match:
  1519. first_match = n
  1520. the_match = match
  1521. best_index = index
  1522. if first_match == absurd_match:
  1523. return -1
  1524. self.start = first_match
  1525. self.match = the_match
  1526. self.end = self.match.end()
  1527. return best_index
  1528. def which(filename):
  1529. """This takes a given filename; tries to find it in the environment path;
  1530. then checks if it is executable. This returns the full path to the filename
  1531. if found and executable. Otherwise this returns None."""
  1532. # Special case where filename contains an explicit path.
  1533. if os.path.dirname(filename) != '':
  1534. if os.access(filename, os.X_OK):
  1535. return filename
  1536. if 'PATH' not in os.environ or os.environ['PATH'] == '':
  1537. p = os.defpath
  1538. else:
  1539. p = os.environ['PATH']
  1540. pathlist = string.split(p, os.pathsep)
  1541. for path in pathlist:
  1542. ff = os.path.join(path, filename)
  1543. if os.access(ff, os.X_OK):
  1544. return ff
  1545. return None
  1546. def split_command_line(command_line):
  1547. """This splits a command line into a list of arguments. It splits arguments
  1548. on spaces, but handles embedded quotes, doublequotes, and escaped
  1549. characters. It's impossible to do this with a regular expression, so I
  1550. wrote a little state machine to parse the command line. """
  1551. arg_list = []
  1552. arg = ''
  1553. # Constants to name the states we can be in.
  1554. state_basic = 0
  1555. state_esc = 1
  1556. state_singlequote = 2
  1557. state_doublequote = 3
  1558. # The state when consuming whitespace between commands.
  1559. state_whitespace = 4
  1560. state = state_basic
  1561. for c in command_line:
  1562. if state == state_basic or state == state_whitespace:
  1563. if c == '\\':
  1564. # Escape the next character
  1565. state = state_esc
  1566. elif c == r"'":
  1567. # Handle single quote
  1568. state = state_singlequote
  1569. elif c == r'"':
  1570. # Handle double quote
  1571. state = state_doublequote
  1572. elif c.isspace():
  1573. # Add arg to arg_list if we aren't in the middle of whitespace.
  1574. if state == state_whitespace:
  1575. # Do nothing.
  1576. None
  1577. else:
  1578. arg_list.append(arg)
  1579. arg = ''
  1580. state = state_whitespace
  1581. else:
  1582. arg = arg + c
  1583. state = state_basic
  1584. elif state == state_esc:
  1585. arg = arg + c
  1586. state = state_basic
  1587. elif state == state_singlequote:
  1588. if c == r"'":
  1589. state = state_basic
  1590. else:
  1591. arg = arg + c
  1592. elif state == state_doublequote:
  1593. if c == r'"':
  1594. state = state_basic
  1595. else:
  1596. arg = arg + c
  1597. if arg != '':
  1598. arg_list.append(arg)
  1599. return arg_list
  1600. # vi:set sr et ts=4 sw=4 ft=python :