Advertisement
Guest User

Untitled

a guest
Apr 24th, 2015
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.23 KB | None | 0 0
  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-
  3. """Execute a child program in a new process"""
  4. import os
  5. import subprocess
  6.  
  7.  
  8.  
  9. def exec_binary(cmd_line_list, cwd=None, stdout=None, stderr=None, verbose=False):
  10. """Invoke an executable file.
  11.  
  12. Example
  13. -------
  14.  
  15. Easy:
  16. >>> exec_binary('ls', verbose=True)
  17.  
  18. Pass parameters:
  19. >>> cmd_line_list = [os.path.join('mypathtobin', 'mybin.exe'), '-conf', myparameter]
  20. >>> if verbose:
  21. >>> cmd_line_list += ['-v']
  22. >>> exec_binary(cmd_line_list, verbose=verbose)
  23.  
  24. Capturing stdout:
  25. >>> import tempfile
  26. >>> [out_fd, out_fname] = tempfile.mkstemp()
  27. >>> try:
  28. >>> exec_binary(cmd_line_list, cwd=bindir, stderr=out_fd, verbose=False)
  29. >>> finally:
  30. >>> os.fsync(out_fd)
  31. >>> os.lseek(out_fd, 0, os.SEEK_SET)
  32. >>> out = os.read(out_fd, 100) # captures stdout
  33. >>> os.close(out_fd)
  34. >>> cleanup_files([out_fname])
  35.  
  36.  
  37. Parameters
  38. ----------
  39. cmd_line_list : list
  40. Passed as first argument to subprocess.Popen.
  41. cwd : string
  42. If not ``None``, change current directory to ``cwd``. Old cwd will be
  43. restored after exit.
  44. stdout : None or open, writeable file stream
  45. If provided, redirect stdout to the given file stream.
  46. stderr : None or open, writeable file stream
  47. If provided, redirect stderr to the given file stream.
  48. verbose : boolean
  49. If False, redirect tool stdout and stderr to /dev/null, unless stdout
  50. parameter is given.
  51.  
  52. """
  53.  
  54. if verbose:
  55. print '* Invoking external tool...'
  56. print ' Command line is: ' + ' '.join(cmd_line_list)
  57.  
  58. # set cwd
  59. if cwd != None:
  60. old_cwd = os.getcwd()
  61. os.chdir(cwd)
  62.  
  63. try:
  64. if not verbose:
  65. devnull = open('/dev/null','w')
  66. if stdout == None:
  67. stdout = devnull
  68. if stderr == None:
  69. stderr = devnull
  70.  
  71. try:
  72. # invoke the tool
  73. proc = subprocess.Popen(cmd_line_list, stdout=stdout, stderr=stderr)
  74. proc.wait()
  75. finally:
  76. if not verbose:
  77. devnull.close()
  78.  
  79. if proc.returncode > 0:
  80. raise Exception('Error executing external tool! Return code ' + str(proc.returncode))
  81.  
  82. finally:
  83. # restore old cwd
  84. if cwd != None:
  85. os.chdir(old_cwd)
  86.  
  87.  
  88.  
  89. def cleanup_files(fname_list, verbose=False):
  90. for fname in fname_list:
  91. if verbose:
  92. print '* Removing file \'' + fname + '\''
  93.  
  94. try:
  95. os.remove(fname)
  96. except:
  97. print '/!\ Warning: could not remove file ' + fname
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement