Package epyunit ::
Module SystemCalls
|
|
1
2 """The module 'epyunit.SystemCalls' provides the controlled execution of subprocesses as units.
3
4 The features are foreseen to support easy setups for unit and regression
5 tests on complex command line options and their combinations.
6 These are in designed to be used in conjunction with
7 with PyUnit, either within Eclipse and PyDev, or from the command line.
8
9 The provided feature set is supported on the platforms: Linux, MacOS, BSD, Solaris, and Windows.
10
11 A quick example call is::
12
13 python -c 'from epyunit.SystemCalls import SystemCalls;x=SystemCalls(**{"proceed":"trace"});x.callit("myscript.sh xOK")'
14
15 or::
16
17 python -c 'from epyunit.SystemCalls import SystemCalls;x=SystemCalls(**{"proceed":"trace"});x.callit("myscript.py xOK")'
18
19 **SECURITY REMARK**: Current version supports for subprocesses the ShellMode only.
20 For test environments in R&D this - hopefully - is perfectly OK,
21 else eventual security issues has to be considered.
22
23 """
24 from __future__ import absolute_import
25
26 __author__ = 'Arno-Can Uestuensoez'
27 __license__ = "Artistic-License-2.0 + Forced-Fairplay-Constraints"
28 __copyright__ = "Copyright (C) 2010-2016 Arno-Can Uestuensoez @Ingenieurbuero Arno-Can Uestuensoez"
29 __version__ = '0.2.1'
30 __uuid__='9de52399-7752-4633-9fdc-66c87a9200b8'
31
32 __docformat__ = "restructuredtext en"
33
34 import os,sys,datetime
35 version = '{0}.{1}'.format(*sys.version_info[:2])
36 if not version in ('2.6', '2.7',):
37 raise Exception("Requires Python-2.6.* or higher")
38
39 import subprocess,platform
40 import shlex,re
41
42
43 _O_STD = 1
44 _O_ERR = 2
45 _O_STR = 3
46 _outdefault = _O_STR
47
48
49 _CSPLTL = re.compile(ur'\r*\n')
50 """Split lines on Windows too including with contained multiple(???) '\r' """
51
53 """Directs the output stream
54 Args:
55 s: String for output
56 _o: Output channel:
57 _O_STD, _O_ERR, _O_STR
58
59 Returns:
60 _o == _O_STD: string
61 _o == _O_ERR: prints to STDERR, returns True
62 _o == _O_STR: prints to STDOUT, returns True
63 else: returns False
64
65 Raises:
66 pass/through
67 """
68 global _outdefault
69 if not _o:
70 _o = _outdefault
71 if _o == _O_STR:
72 return s
73 elif _o == _O_ERR:
74 sys.stderr.write(s)
75 else:
76 sys.stdout.write(s)
77 return True
78
80 """Common error within epyunit.SystemCalls.
81 """
82 pass
83
85 """Timeout of subprocess epyunit.SystemCalls.
86 """
87 pass
88
89
90
92 """Error from subprocess.
93 """
95 """Calls the 'exceptions.SystemExit' with pass through of parameters.
96
97 Args:
98 **kargs: Additional parameters specific for ePyUnit
99 where the interface is not actually clear.
100 These are removed before the pass-through call.
101
102 exitval: Replaces 'exceptions.SystemExit.code', the
103 first param value when of type 'int'. The default
104 is defined as '1'.
105
106 REMARK: Did not found an official interface for
107 'exceptions.SystemExit.__init__', thus opted
108 to temporary injection.
109
110 exitmsg: Defines display test.
111
112 Returns:
113 None/Itself
114
115 Raises:
116 itself
117
118 """
119 _code = kargs.get('exitval')
120 if _code:
121 kargs.pop('exitval')
122 _msg = kargs.get('exitmsg')
123 if _msg:
124 kargs.pop('exitmsg')
125 super(SystemCallsExceptionSubprocessError,self).__init__(*args,**kargs)
126 if _code:
127 self.code = _code
128 if _msg:
129 self.message = _msg
130 pass
131
133 """Wraps system calls for the execution of subprocesses.
134 For supported parameters refer to 'epyunit.SystemCalls.setkargs()'.
135
136 """
138 """Prepares the interface for subprocess calls with output cache.
139 The initial setup includes the preparation of the result
140 cache for the response data from stdout and stderr.
141
142 Args:
143 **kargs:
144 Parameters specific for the operations,
145 passed through to **SystemCalls.setkargs**
146 `[see setkargs] <#setkargs>`_.
147
148 Returns:
149 When successful returns 'True', else returns either 'False', or
150 raises an exception.
151 Success is the complete addition only, thus one failure returns
152 False.
153
154 *REMARK*
155 When errors occur in buffered mode the
156 output from the called process is possibly
157 not completely cached. In that case
158 switch to 'dialogue' mode in order to get an
159 unbuffered console display.
160
161 Raises:
162 passed through exceptions:
163
164 """
165
166 self.console = 'cli'
167 self.bufsize = 16384
168
169
170 self.emptyiserr = False
171 """The subprocess call for an empty string is 'success',
172 thus this has to be checked independently for eventually erroneously missing call string
173 """
174
175 self.errasexcept = False
176
177 if sys.platform == 'win32':
178 self.myexe = self._mode_batch_win
179 else:
180 self.myexe = self._mode_batch_posix
181
182 self.out = 'pass'
183 self.outtarget = 'stdout'
184 self.passerr = False
185 self.proceed = 'doit'
186 self.raw = False
187 self.useexit = True
188 self.usestderr = False
189 self.verbose = 0
190
191 self.exectype = 'inproc'
192 self.synctype = 'async'
193 self.forcecmdcall = 'list'
194 self.tsig = 'TERM'
195 self.tmax = 15
196
197
198 self._appname = None
199 self._testid = None
200 self._timestamp = None
201 self._environment = None
202
203 self.setkargs(**kargs)
204 pass
205
206 - def callit(self,cmdcall,**kargs):
207 """Executes a prepared 'cmdcall' synchronous by the a preset function pointer 'self.myexe'.
208 For the full scope of call parameters including multiple subprocesses use the method
209 `[see create] <#create>`_.
210
211 Args:
212 cmdcall:
213 A prepared call, either shell-style call-string,
214 or a list in accordance to the call convention of
215 'subprocess' package. The 'shell' parameter is
216 by default set in accordance to the provided type.
217
218 **kargs:
219 Parameters specific for the operations,
220 passed through to **SystemCalls.setkargs**
221 `[see setkargs] <#setkargs>`_.
222
223 The following are also evaluated instantly within
224 the call prologue:
225
226 proceed:
227 Changes predefined value and dispatches to the subcall.
228
229 raw:
230 Suppress the split of lines for
231 stdout and stderr.
232
233
234 Returns:
235 Result of call, the format is:
236
237 ret[0]::= exit value
238
239 ret[1]::= STDOUT as non-processed string.
240
241 ret[2]::= STDERR as non-processed string.
242
243 *REMARK*
244 When errors occur in buffered mode the
245 output from the called process is possibly
246 not completely cached, e.g. in case of exeptions.
247 In that case try switching to 'dialogue' mode in order
248 to get an unbuffered console display. This will deliver
249 - hopefully - the complete output.
250
251 Raises:
252 SystemCallsTimeout:
253 Rised in case of timeout by tmax/tsig.
254 Terminates also the outstanding subprocess.
255
256 passed through exceptions:
257
258 """
259 proceed = self.proceed
260 _raw = False
261 for k,v in kargs.iteritems():
262 if k=='proceed':
263 proceed=self.get_proceed(v)
264 kargs.pop('proceed')
265 elif k=='raw':
266 _raw=True
267 kargs.pop('raw')
268 self.setkargs(**kargs)
269
270 ret=[1,]
271 if proceed=="print":
272 print str(cmdcall)
273 return [0,[],[]]
274
275 elif proceed=="trace":
276 print >>sys.stderr, "TRACE:"+str(cmdcall)
277 ret=self.myexe(cmdcall,**kargs)
278
279 elif proceed=="doit":
280 ret=self.myexe(cmdcall,**kargs)
281
282 if ret[0] not in (0,5):
283 if self.verbose>0:
284 print "ret:"+str(ret)+" =>call:"+str(cmdcall)
285
286 if not _raw and not self.raw:
287 ret = self.splitLines(ret)
288 return ret
289
291 """Cancels a running process.
292 """
293 if not proc:
294 proc = self.p
295
296 pass
297
299 """Executes a prepared 'cmdcall' with a variety of parameters.
300
301 For now a placeholder only - implementation is going to follow soon.
302
303 """
304 if not proc:
305 proc = self.p
306
307 pass
308
310 """Streams result list 'ret' in selected format to selected outtarget.
311
312 Args:
313 ret: Data to be displayed.
314
315 **kargs:
316
317 outtarget: The target of display:
318
319 str: return as formatted string
320
321 stdout: print to sys.stdout
322
323 stderr: print to sys.stderr
324
325 out: Output for display, valid:
326
327 csv : CSV with sparse records
328
329 pass : pass through STDOUT and STDERR from subprocess
330
331 repr : Python 'repr()'
332
333 str : Python 'str()'
334
335 xml : XML
336
337 default:=self.out
338
339 Returns:
340 When successful returns
341
342 outtarget=='str': returns a printable formatted string
343
344 outtarget in ('stdout', 'stderr',):
345
346 'True': for success
347
348 'False': for failure
349
350 Raises:
351 passed through exceptions:
352
353 """
354 _target = kargs.get('outtarget',self.outtarget)
355 if _target == 'str':
356 _t = _O_STR
357 elif _target == 'stderr':
358 _t = _O_ERR
359 else:
360 _t = _O_STD
361 self._oc = ""
362
363 _out = kargs.get('out',self.out)
364
365 def _output(s,_o=None):
366 if not _o:
367 _o = _t
368 if _o == _O_STR:
369 self._oc += s
370 elif _o == _O_ERR:
371 sys.stderr.write(s)
372 else:
373 sys.stdout.write(s)
374
375
376 if _out in ("pass","passall","raw",):
377 if ret[1]:
378 if type(ret[1]) == list:
379 _output("\n".join(ret[1])+'\n')
380 else:
381 _output(ret[1])
382 if ret[2]:
383 if _t == _O_STD:
384 _tx = _O_ERR
385 else:
386 _tx = _t
387 if type(ret[2]) == list:
388 _output("\n".join(ret[2])+'\n',_tx)
389 else:
390 _output(ret[2],_tx)
391
392 elif _out == "repr":
393 _output(repr(ret))
394
395 elif _out == "str":
396 _output("exit: "+str(ret[0])+'\n')
397 _output("stdout: "+str(ret[1])+'\n')
398 _output("stderr: "+str(ret[2])+'\n')
399
400 elif _out == "xml":
401 _output("""<?xml version="1.0" encoding="UTF-8"?>\n""")
402
403
404 _dn = datetime.datetime.now()
405 _date=str(_dn.year)+'-'+str(_dn.month)+'-'+str(_dn.day)
406 _time=str(_dn.hour)+':'+str(_dn.minute)+':'+str(_dn.second)
407 _head="<test-result "
408 if self._testid:
409 _head += " id="+str(self._testid)
410 if self._appname:
411 _head += " appname='"+str(self._appname)+"'"
412 if self._timestamp:
413 _head += " date='"+str(_date)+"'"
414 _head += " time='"+str(_time)+"'"
415 if self._environment:
416 _head += " host='"+str(self._host)+"'"
417 _head += " user='"+str(self._user)+"'"
418 _head += " os='"+str(self._os)+"'"
419 _head += " osver='"+str(self._osver)+"'"
420 _head += " dist='"+str(self._dist)+"'"
421 _head += " distver='"+str(self._distver)+"'"
422 _head += ">"
423
424 _output(str(_head)+'\n')
425
426
427 _output(" <exit-code>"+str(ret[0])+"</exit-code>\n")
428
429
430 _output(" <stdout>\n")
431 lx = 0
432 for l in ret[1]:
433 _output(" <line cnt="+str(lx)+">"+str(l)+"</line>\n")
434 lx += 1
435 _output(" </stdout>\n")
436
437
438 _output(" <stderr>\n")
439 lx = 0
440 for l in ret[2]:
441 _output(" <line cnt="+str(lx)+">"+str(l)+"</line>\n")
442 lx += 1
443 _output(" </stderr>\n")
444
445 _output("""</test-result>""")
446
447 elif _out == "csv":
448 _head = None
449
450 if self._testid:
451 if _head: _head = ';'
452 _head += "testid"
453 if self._appname:
454 if _head: _head = ';'
455 _head += ";appname"
456 if self._timestamp:
457 if _head: _head = ';'
458 _head += ";date;time"
459 if self._environment:
460 if _head: _head = ';'
461 _head += ";host;user;os;osver;dist;distver"
462
463 if _head: _head = ';'
464 else: _head = ""
465 _head += "exitcode;total-lines;stdout-line;stdout;stderr-line;stderr"
466
467 _output(str(_head)+'\n')
468
469
470 _dn = datetime.datetime.now()
471 _date=str(_dn.year)+'-'+str(_dn.month)+'-'+str(_dn.day)
472 _time=str(_dn.hour)+':'+str(_dn.minute)+':'+str(_dn.second)
473
474 _lxtot=0
475
476
477 _recpre = None
478
479
480 if self._testid:
481 if _recpre: _recpre += ';'
482 _recpre += str(self._testid)
483 if self._appname:
484 if _recpre: _recpre += ';'
485 _recpre += str(self._appname)
486 if self._timestamp:
487 if _recpre: _recpre += ';'
488 _recpre += str(_date)+";"+str(_time)
489 if self._environment:
490 if _recpre: _recpre += ';'
491 _recpre += str(self._host)+";"+str(self._user)+";"+str(self._os)+";"+str(self._osver)+";"+str(self._dist)+";"+str(self._distver)
492
493 _lx1 = 0
494 _lx2 = 0
495
496 _r1 = len(ret[1])
497 _r2 = len(ret[2])
498 if _r1 > _r2:
499 _rmax = _r1
500 else:
501 _rmax = _r2
502
503 for _ri in range(_rmax):
504 _lxtot +=1
505 _rec = _recpre
506 if _rec: _rec += ';'
507 else: _rec = ''
508 _rec += str(ret[0])+";"+str(_lxtot)
509
510
511 if len(ret[1]) > _ri:
512 if _rec: _rec += ';'
513 else: _rec = ''
514 _rec += str(_lx1)+";"+str(ret[1][_ri])
515 _lx1 += 1
516 else:
517 if _rec: _rec += ';;'
518 else: _rec = ';'
519
520
521 if len(ret[2]) > _ri:
522 if _rec: _rec += ';'
523 else: _rec = ''
524 _rec += str(_lx2)+";"+str(ret[2][_ri])
525 _lx2 += 1
526 else:
527 if _rec: _rec += ';;'
528 else: _rec = ';'
529
530 _output(str(_rec)+'\n')
531
532 if _t == _O_STR:
533 return self._oc
534 return True
535
537 """Verifies valid proceed type."""
538 if s in ('print','trace', 'doit'):
539 return s
540 else:
541 raise Exception('STATE:ERROR:proceed not supported:'+str(s))
542
543 - def _mode_batch_postproc(self,cmdcall,**kargs):
544 """Postprocess
545 """
546 pass
547
549 """Creates and calls a process instance on POSIX based systems.
550
551 The IO by stdout/stdin/stderr are redirected. Supports
552 shell-style parameters only.
553
554 Args:
555 cmdcall:
556 A prepared shell-style call.
557
558 **kargs:
559
560 mode:
561 Execution mode for the created process instance.
562 * batch:
563 Proceeds headless, collects reponses from STDOUT
564 and STDERR.
565
566 * dialogue
567 Proeceeds interactive.
568
569 env:
570 Inhereted environment, by default the current.
571
572 tmax:
573 Timeout in seconds.
574
575 tsig:
576 Termination signal, default is KILL.
577
578 Returns:
579 When successful returns 'True', else returns either 'False', or
580 raises an exception.
581
582 Raises:
583 for parameter 'errasexcept': SystemCallsExceptionSubprocessError
584 passed through exceptions:
585
586 For further information refer to 'console' option of constructor/setkargs.
587
588 """
589 if self.emptyiserr and ( not cmdcall or cmdcall.lstrip(' ') == ''):
590 return [2,'', 'ERROR:MissingCallstr']
591
592 ret=[1,]
593 _env = kargs.get('env',os.environ)
594 _mode = kargs.get('mode','batch')
595
596 if type(cmdcall) in (str,unicode,):
597 _shell = True
598 elif type(cmdcall) is list:
599 _shell = False
600
601 _close_fds = False
602 self.stdioIN = subprocess.PIPE
603 self.stdioOUT = subprocess.PIPE
604 self.stdioERR = subprocess.PIPE
605
606
607 self.p=subprocess.Popen(
608 cmdcall,
609 shell=_shell,
610 bufsize=self.bufsize,
611 stdin=self.stdioIN,
612 stdout=self.stdioOUT,
613 stderr=self.stdioERR,
614 close_fds=_close_fds,
615 env=_env
616 )
617
618
619 self.stdin=self.p.stdin
620 self.stdout=self.p.stdout
621 self.stderr=self.p.stderr
622 self.res=self.p.communicate()
623 self.p.poll()
624
625 _errcond = False
626 if self.useexit and self.usestderr:
627 if self.p.returncode or self.res[1]:
628 _errcond = True
629 elif self.useexit and self.p.returncode:
630 _errcond = True
631 elif self.usestderr and self.res[1]:
632 _errcond = True
633
634 if _errcond and self.errasexcept:
635
636 if self.res[0]:
637 sys.stdout.write(self.res[0])
638 if self.res[1]:
639 sys.stderr.write(self.res[1])
640
641
642 raise SystemCallsExceptionSubprocessError(self.p.returncode,**{'exitmsg':"FROM:"+str(cmdcall) +"\n",})
643
644 elif _errcond and self.passerr:
645
646 if self.res[0]:
647 sys.stdout.write(self.res[0])
648 if self.res[1]:
649 sys.stderr.write(str(self.res[1]))
650
651 sys.exit(self.p.returncode)
652
653 elif _errcond and not self.p.returncode and self.usestderr:
654 ret[0] = 1
655 ret.extend(self.res)
656 return ret
657
658 else:
659 ret[0]=self.p.returncode
660 ret.extend(self.res)
661 return ret
662
664 """Creates and calls a process instance on Windows based systems.
665
666 The IO by stdout/stdin/stderr are redirected. Supports
667 shell-style parameters only.
668
669 Args:
670 cmdcall:
671 A prepared shell-style call.
672
673 **kargs:
674
675 mode:
676 Execution mode for the created process instance.
677 * batch:
678 Proceeds headless, collects reponses from STDOUT
679 and STDERR.
680
681 * dialogue
682 Proeceeds interactive.
683
684 env:
685 Current environment.
686
687 tmax:
688 Timeout in seconds.
689
690 tsig:
691 Termination signal, default is KILL.
692
693 Returns:
694 When successful returns 'True', else returns either 'False', or
695 raises an exception.
696
697 Raises:
698 for parameter 'errasexcept': SystemCallsExceptionSubprocessError
699 passed through exceptions:
700
701 For further information refer to 'console' option of constructor/setkargs.
702
703 """
704 if self.emptyiserr and ( not cmdcall or cmdcall.lstrip(' ') == ''):
705 return [2,'', 'ERROR:MissingCallstr']
706
707 ret=[1,]
708 _env = kargs.get('env',None)
709
710 _env = os.environ
711
712 _mode = kargs.get('mode','batch')
713
714 if type(cmdcall) is str:
715 _shell = True
716 elif type(cmdcall) is list:
717 _shell = False
718
719 si = subprocess.STARTUPINFO()
720 si.dwFlags = subprocess.STARTF_USESHOWWINDOW
721 si.dwFlags |= subprocess.CREATE_NEW_PROCESS_GROUP
722
723
724
725
726
727
728 self.stdio = subprocess.PIPE
729
730 _close_fds = False
731 self.p=subprocess.Popen(
732 cmdcall,
733 shell=_shell,
734 bufsize=self.bufsize,
735 stdin=self.stdio,
736 stdout=self.stdio,
737 stderr=self.stdio,
738 close_fds=_close_fds,
739 env=_env,
740 startupinfo=si,
741 )
742
743
744 self.stdin=self.p.stdin
745 self.stdout=self.p.stdout
746 self.stderr=self.p.stderr
747 self.res=self.p.communicate()
748
749 self.p.poll()
750
751 _errcond = False
752 if self.useexit and self.usestderr:
753 if self.p.returncode or self.res[1]:
754 _errcond = True
755 elif self.useexit and self.p.returncode:
756 _errcond = True
757 elif self.usestderr and self.res[1]:
758 _errcond = True
759
760 if _errcond and self.errasexcept:
761
762 if self.res[0]:
763 sys.stdout.write(self.res[0])
764 if self.res[1]:
765 sys.stderr.write(self.res[1])
766
767
768 raise SystemCallsExceptionSubprocessError(self.p.returncode,**{'exitmsg':"FROM:"+str(cmdcall) +"\n",})
769
770 elif _errcond and self.passerr:
771
772 if self.res[0]:
773 sys.stdout.write(self.res[0])
774 if self.res[1]:
775 sys.stderr.write(str(self.res[1]))
776
777 sys.exit(self.p.returncode)
778
779 elif _errcond and not self.p.returncode and self.usestderr:
780 ret[0] = 1
781 ret.extend(self.res)
782
783 else:
784 ret[0]=self.p.returncode
785 ret.extend(self.res)
786
787
788 self.p.stderr.close()
789 self.p.stdout.close()
790
791
792
793
794
795
796
797
798
799
800
801
802
803 return ret
804
806 """Internal call reference for processing an interactive dialogue call.
807
808 Supports shell-style parameters only.
809
810 For further information refer to 'console' option of constructor/setkargs.
811
812 """
813
814
815 if self.emptyiserr and ( not cmdcall or cmdcall == ''):
816 return [2,'', 'ERROR:MissingCallstr']
817
818 ret=[0,]
819 try:
820 self.p=subprocess.check_call(
821 cmdcall,
822 shell=True,
823 bufsize=self.bufsize
824 )
825 except subprocess.CalledProcessError as e:
826 try:
827 ret[0]=self.p.returncode
828 ret.append(self.p.output)
829 except:
830 ret[0]=99
831 ret.append(str(e))
832 pass
833 return ret
834
836 """Sets provided parameters for the subprocess call context.
837
838 Applicable for the initial call of self.__init__(),
839 and later modification. Called for each start of
840 a subprocess in order to update optional the specific
841 call context modification.
842
843 Args:
844 **kargs: Parameter specific for the operation,
845
846
847 bufsize:
848 The size of the output buffer for the called
849 subprocess, refer to **subprocess.Popen**.
850 Default value is -1.
851
852 console ('cli','dialogue')
853 ffs ('batch','ui','gtk', 'qt')
854
855 cli:
856 Works in batch mode, particularly the
857 stdin, stdout, and stderr streams are
858 caught into a string buffer by the
859 calling process via a pipe. The content
860 is passed after termination of the
861 called sub-process.
862
863 dialogue:
864 Works without buffered io streams.
865 Thus allows for interaction, but not
866 post-processing.
867
868 verbose:
869 Verbose.
870
871 debug:
872 Sets debug for rule data flow.
873
874 emptyiserr:
875 Treats passed empty call strings as error.
876 The applied 'subprocess.Popen()' treats them as
877 success, which may cover errors in generated
878 call strings, particularly in loops.
879
880 default := False
881
882 env:
883 Environment to be passed through to the subprocess.
884
885 Default := current
886
887 errasexcept:
888 Passes errors as exceptions, transforms the resuls from
889 subprocesses into Exceptions data. Exits the process.
890
891 default := False
892
893 exectype:
894 Type of execution.
895 * inproc:
896 Calls 'Popen' directly from within the process.
897
898 * bythread:
899 Starts an intermediate thread within current
900 process and executes 'Popen'.
901
902 * byfork
903 Starts an intermediate process by fork and
904 executes 'Popen'.
905
906 forcecmdcall:
907 Forces type of the command call option passed to 'Popen'.
908 * shell
909 * list
910
911 out: Output for display. Supported types are:
912
913 csv:
914 CSV seperated by ';', with sparse records
915
916 pass:
917 Pass through STDOUT and STDERR from
918 subprocess
919
920 repr:
921 Python 'repr()'
922
923 str:
924 Python 'str()'
925
926 xml:
927 XML
928
929 passerr:
930 Passes errors from subprocesses transparently
931 through by stdout, stderr, and exit code. Exits
932 the process.
933
934 default := False
935
936 proceed ('print','trace', 'doit')
937 print - trace only
938
939 trace - execute and trace
940
941 doit - execute
942
943 raw:
944 Pass through STDOUT and STDERR.
945
946 rules:
947 Sets the rules object.
948
949 synctype:
950 Type of call synchronization.
951 * async:
952 Executes the subprocess asynchronously, this e.g. enables
953 in current implementation for platform independent timeouts.
954
955 * sync:
956 Executes synchronously, thus blocks any other execution.
957
958 tsig:
959 Termination signal, default is KILL.
960
961 tmax:
962 Timeout in seconds.
963
964 useexit:
965 Use exit code for error detection of subprocess.
966
967 default := True
968
969 usestderr:
970 Use 'sys.stderr' output for error detection of subprocess.
971 When set to 'True', the presence of a string is treated as error
972 condition.
973
974 default := False
975
976 verbose:
977 Sets verbose for rule data flow.
978
979 Returns:
980 When successful returns 'True', else returns either 'False', or
981 raises an exception.
982 Success is the complete addition only, thus one failure returns
983 False.
984
985 Raises:
986 passed through exceptions:
987
988 """
989 for k,v in kargs.iteritems():
990 if k=='bufsize':
991 self.bufsize=int(v)
992 elif k=='console':
993 self.console=v
994 if v == 'cli':
995 self.out = v
996 if v == 'dialogue':
997 self.myexe=self._mode_dialogue
998 elif v=='batch':
999 raise Exception('STATE:ERROR:console not supported:'+str(v))
1000 elif v in ('ui','gtk', 'qt'):
1001 pass
1002 else:
1003 self.myexe=self._mode_dialogue
1004 elif k=='debug':
1005 self.debug=v
1006 elif k=='emptyiserr':
1007 self.emptyiserr=v
1008 elif k=='env':
1009 self.env = v
1010
1011
1012
1013 pass
1014 elif k=='errasexcept':
1015 self.errasexcept=v
1016 elif k=='out':
1017 self.out = v
1018 if v in ('csv', 'pass', 'repr', 'str', 'xml', ):
1019 pass
1020 else:
1021 raise SystemCallsException("Unknown output type:"+str(self.out))
1022 elif k=='passerr':
1023 self.passerr=v
1024 elif k=='proceed':
1025 self.proceed=self.get_proceed(v)
1026 elif k=='raw':
1027 self.raw=v
1028 elif k=='rules':
1029 self.rules=v
1030 elif k=='useexit':
1031 self.useexit=v
1032 elif k=='usestderr':
1033 self.usestderr=v
1034 elif k=='verbose':
1035 self.verbose=v
1036
1037
1038
1039 return True
1040
1042 """Converts the raw string fields including '\n' of a return value into line arrays.
1043
1044 Args:
1045 oldres: The raw result of a previous call.
1046
1047 Returns:
1048 Result of call, the format is:
1049
1050 ret[0]::=exit value
1051
1052 ret[1]::=list of lines from former stdout output, each as
1053 a partial non-processed string.
1054
1055 ret[2]::=list of lines from former stderr output, each as
1056 a partial non-processed string.
1057
1058 Raises:
1059 passed through exceptions:
1060
1061 """
1062 res = [oldres[0],[],[]]
1063
1064 if len(oldres) > 1:
1065
1066 res[1] = _CSPLTL.split(oldres[1])
1067 if res[1] and res[1][-1] == '':
1068 res[1].pop()
1069 if res[1] and res[1][0] == '':
1070 res[1].pop(0)
1071
1072 if len(oldres) > 2:
1073
1074 res[2] = _CSPLTL.split(oldres[2])
1075 if res[2] and res[2][-1] == '':
1076 res[2].pop()
1077 if res[2] and res[2][0] == '':
1078 res[2].pop(0)
1079 return res
1080
1082 """Prints preset call parameters.
1083 """
1084 ret = ""
1085 ret += "\nbufsize = "+str(self.bufsize)
1086 ret += "\nconsole = "+str(self.console)
1087
1088 if getattr(self, 'debug', None):
1089 ret += "\ndebug = "+str(self.debug)
1090
1091 ret += "\nemptyiserr = "+str(self.emptyiserr)
1092 ret += "\nenv = "+str(self.env)
1093 ret += "\nerrasexcept = "+str(self.errasexcept)
1094 ret += "\nmyexe = "+str(self.myexe)
1095 ret += "\nout = "+str(self.out)
1096 ret += "\npasserr = "+str(self.passerr)
1097 ret += "\nproceed = "+str(self.proceed)
1098 ret += "\nraw = "+str(self.raw)
1099 ret += "\nrules = "+str(self.rules)
1100 ret += "\nuseexit = "+str(self.useexit)
1101 ret += "\nusestderr = "+str(self.usestderr)
1102
1103 if getattr(self, 'verbose', None):
1104 ret += "\nverbose = "+str(self.get('verbose'))
1105
1106 return ret
1107
1109 """Prints the current representation of call parameters for subprocesses.
1110 """
1111 ret = "{"
1112 ret += "'bufsize': "+str(self.bufsize)
1113 ret += ", 'console': "+str(self.console)
1114
1115 if getattr(self, 'debug', None):
1116 ret += ", 'debug': "+str(self.get('debug'))
1117
1118 ret += ", 'emptyiserr': "+str(self.emptyiserr)
1119 ret += ", 'env': "+str(self.env)
1120 ret += ", 'errasexcept': "+str(self.errasexcept)
1121 ret += ", 'myexe': "+str(self.myexe.__name__)
1122 ret += ", 'out': "+str(self.out)
1123 ret += ", 'passerr': "+str(self.passerr)
1124 ret += ", 'proceed': "+str(self.proceed)
1125 ret += ", 'raw': "+str(self.raw)
1126 ret += ", 'rules': "+str(self.rules)
1127 ret += ", 'useexit': "+str(self.useexit)
1128 ret += ", 'usestderr': "+str(self.usestderr)
1129
1130 if getattr(self, 'verbose', None):
1131 ret += ", 'verbose': "+str(self.get('verbose'))
1132 ret += "}"
1133 return ret
1134