Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import fcntl
- import os
- import select
- import shlex
- import subprocess
- import sys
- class bcolors:
- HEADER = '\033[95m'
- OKBLUE = '\033[94m'
- OKGREEN = '\033[92m'
- WARNING = '\033[93m'
- FAIL = '\033[91m'
- ENDC = '\033[0m'
- BOLD = '\033[1m'
- UNDERLINE = '\033[4m'
- def runtext(command, stdin = None, output = None, encoding = None):
- if(output == None):
- output = "all"
- if(encoding == None):
- encoding = "utf-8"
- ret = subprocess.CompletedProcess(command, 0)
- process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE, bufsize=1, encoding=encoding)
- if(stdin != None):
- process.stdin.write(stdin)
- process.stdin.write("\n")
- ##subprocess.[stderr|stdout].readline() lock the script. This is so it isn't so.
- flags = fcntl.fcntl(process.stdout, fcntl.F_GETFL) # get current p.stdout flags
- fcntl.fcntl(process.stdout, fcntl.F_SETFL, flags | os.O_NONBLOCK)
- flags = fcntl.fcntl(process.stderr, fcntl.F_GETFL) # get current p.stderr flags
- fcntl.fcntl(process.stderr, fcntl.F_SETFL, flags | os.O_NONBLOCK)
- flags = fcntl.fcntl(process.stdin, fcntl.F_GETFL) # get current p.stderr flags
- fcntl.fcntl(process.stdin, fcntl.F_SETFL, flags | os.O_NONBLOCK)
- while(True):
- while sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
- line = sys.stdin.readline()
- if line:
- print(line)
- process.stdin.write(line)
- #else: # an empty line means stdin has been closed
- #print('eof')
- #exit(0)
- else:
- #print("41")
- _output = ''
- error = ''
- try:
- temp = process.stdout.readline()
- except OSError:
- temp = ''
- while(temp != ''):
- #print("49")
- _output += temp
- try:
- temp = process.stdout.readline()
- except OSError:
- temp = ''
- try:
- #print("57")
- temp = process.stderr.readline()
- except OSError:
- temp = ''
- while(temp != ''):
- #print("62")
- error += temp
- try:
- temp = process.stderr.readline()
- except OSError:
- temp = ''
- if(_output == '' and error == '' and process.poll() != None):
- break
- if(_output):
- #print("out:")
- ret.stdout = ar.string.append(_output, ret.stdout)
- if(output == "all"):
- print(ar.string.trim(_output))
- #print(_output)
- if(error):
- #print("err:")
- ret.stderr = ar.string.append(error, ret.stderr)
- if(output == "all" or output == "error"):
- print(bcolors.FAIL + ar.string.trim(error) + bcolors.ENDC)
- #print(error)
- ret.returncode = process.poll()
- ##If we raise here, ret is not returned and output and error information cannot be accessed.
- #ret.check_returncode()
- return ret
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement