def monitor_srslte(self, proc):
        """ Monitor for crashes and restart srsLTE"""
        # TODO
        global EXIT
        out = []
        sleep(1)
        nbsr = NBSR(proc.stdout)
        line = ''
        while not EXIT:
            line = nbsr.readline(int(self.config["general"]["crash_timeout"]))
            if line is not None:
                self.logger.debug(line.decode("ascii").rstrip())
            out.append(line)

            if proc.poll() is not None or line is None:
                self.logger.warning(f"srsUE has exited unexpectedly")
                try:
                    self.logger.warning(
                        f"It's dying words were: {out[-2].decode('ascii').rstrip()}"
                    )
                except IndexError as e:
                    pass
                proc.kill()
                self.update_earfcn_list()
                proc = self.start_srslte()
                self.monitor_srslte(proc)
Beispiel #2
0
def resetCode(args):
    global aiProc, advStdout
    if (aiProc != None):
        aiProc.kill()

    aiProc = Popen(['sh', pathToRun], stdin=PIPE, stdout=PIPE, bufsize=0)
    advStdout = NBSR(aiProc.stdout)
Beispiel #3
0
def runTestcase(testplan):
    subprocess.call("rm -f *.card; rm .*.card", shell=True)
    subprocess.call("rm -f *.auth", shell=True)
    print("Exec bank process")
    popen = subprocess.Popen(["./bank"], stdout=subprocess.PIPE)
    atexit.register(popen.kill)
    print("Read first line")
    nbsr = NBSR(popen.stdout)
    print(nbsr.readline(5))
    error = False
    print("--" * 30)

    for test in testplan:
        same = runExceution(nbsr, test["input"], test["bank"], test["atm"])
        print("--" * 30)
        if not same:
            error = True
            break

    subprocess.call("rm -f *.card", shell=True)
    subprocess.call("rm -f *.auth", shell=True)
    popen.terminate()
    print("BANK SIGTERM")
    popen.wait(10.0)
    if popen.returncode is None:
        popen.kill()
        print("ERROR BANK: did not exit in time")
        error = True
    elif popen.returncode != 0:
        print("ERROR BANK: did not exit with code 0")
        error = True
    else:
        print("BANK EXIT OK")
    return not (error)
Beispiel #4
0
    def run_instrument(self):
        context = self.context

        start = int(time.time())
        args = ['adb', '-s', context.ip, 'shell', 'am', 'instrument', '-w', '-r', '-e', 'debug', 'false',
                context.appPkgName + '.test/android.support.test.runner.AndroidJUnitRunner']
        result = ''
        child = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE)

        nbsr = NBSR(child.stdout)

        # 若进程尚未结束, popen() 返回 none
        while child.poll() is None:
            logging.debug("child.poll() is none")
            now = int(time.time())
            costTime = (now - start) / 60
            if costTime < context.timeout and costTime < 100:
                logging.debug('cost time:' + str(costTime))
                # result += child.stdout.readline()
                output = nbsr.readline(30)
                if not output:
                    logging.debug("no output")
                else:
                    result += output
            else:
                logging.debug('time out, the process will be killed')
                child.kill()
                child.wait()
                break
        logging.debug("child is over !!")
        return context.make_report(result)
Beispiel #5
0
def run_telly():
    global telly_proc, telly_stream

    # run Telly
    print("Running Telly.  Configured to run on IP " + CONFIG_LISTEN_ADDY + "...")

    # ./telly -b 192.168.29.222:6077
    telly_proc = subprocess.Popen(["./telly", "-b", CONFIG_LISTEN_ADDY + ":6077"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    telly_stream = NBSR(telly_proc.stdout)
Beispiel #6
0
	def CreateChildProcess(self,Execution_Command,Executable_File):
		if platform == 'win32' and Executable_File.endswith('.exe'):
			self.ChildProcess = Popen (str(Executable_File), stdin = PIPE, stdout = PIPE, bufsize=0)
		elif platform == "darwin" or platform == "linux" or platform == "linux2":
			self.ChildProcess = Popen ([Execution_Command, Executable_File], stdin = PIPE, stdout = PIPE, bufsize=0,preexec_fn=os.setsid)
		else:
			self.ChildProcess = Popen ([Execution_Command, Executable_File], stdin = PIPE, stdout = PIPE, bufsize=0)
			# self.ChildProcess = Popen (str(Executable_File), stdin = PIPE, stdout = PIPE, bufsize=0)
		self.ModifiedOutStream = NBSR(self.ChildProcess.stdout)
Beispiel #7
0
def init_processes(length):
    """Send init command to all processes"""
    for i in range(1, length):
        print('{} : {}'.format(i - 1, sys.argv[i]))
        process = Popen(
            sys.argv[i],
            bufsize=0,
            stdin=PIPE,
            stdout=PIPE,
            #stdout=io.FileIO('out{}.txt'.format(i - 1), 'w'),
            stderr=STDOUT)
        nbsr = NBSR(process.stdout, doprint=False, idd=i - 1)
        #NBSR(process.stdin, doprint=True, idd=i+9)
        PROCESSES.append({'process': process, 'nbsr': nbsr, 'id': i - 1})

    if not communicate(PROCESSES[PROG_ARB], 'init\n', 2,
                       except_none=True) == "OK":
        print('ARBITRATOR failed for [init] command.')

    val1 = communicate(PROCESSES[PROG_IA1], 'init\n', 2,
                       except_none=True) == "OK"
    val2 = communicate(PROCESSES[PROG_IA2], 'init\n', 2,
                       except_none=True) == "OK"
    for i, val in enumerate([val1, val2]):
        if not val:
            print('PROG_{} failed for [init] command.'.format(i))
    check = complicated(val1, val2)
    if check < 2:
        end(check)

    name1 = communicate(PROCESSES[PROG_IA1], 'name\n', 2)
    name2 = communicate(PROCESSES[PROG_IA2], 'name\n', 2)
    val1 = name1 is not None
    val2 = name2 is not None
    for i, val in enumerate([val1, val2]):
        if not val:
            print('PROG_{} failed for [name] command.'.format(i))
    check = complicated(val1, val2)
    if check < 2:
        end(check)
    PROCESSES[PROG_IA1]['name'] = name1
    PROCESSES[PROG_IA2]['name'] = name2

    if length == 5:
        if not communicate(PROCESSES[PROG_DIS], 'init\n', 2,
                           except_none=True) == "OK":
            print('DISPLAYER failed for [init] command.')
        if communicate(PROCESSES[PROG_DIS],
                       'names {};{}\n'.format(name1, name2),
                       2.0,
                       except_none=True) != "OK":
            print('DISPLAYER failed for [names] command.')
def subprocess_init():
    for device in devices:
        process = subprocess.Popen(['/bin/bash'], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
        if device.startswith('ttyUSB'):
            sys.stdout.write('>make login TARGET={} MOTES=/dev/{}\n'.format(platform, device))
            process.stdin.write('make login TARGET={} MOTES=/dev/{}\n'.format(platform, device))
        elif device.startswith('ttyACM'):
            sys.stdout.write('>make login TARGET={} BOARD=sensortag/cc2650 PORT=/dev/{}\n'.format(platform, device))
            process.stdin.write('make login TARGET={} BOARD=sensortag/cc2650 PORT=/dev/{}\n'.format(platform, device))

        subprocesses.append(process)
        sr = NBSR(process.stdout)
        streamreaders.append(sr)
 def CreateChildProcess(self, Execution_Command, Executable_File,
                        args_list):
     if platform == "darwin" or platform == "linux" or platform == "linux2":
         self.ChildProcess = Popen([Execution_Command, Executable_File] +
                                   args_list,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   bufsize=0,
                                   preexec_fn=os.setsid)
     else:
         self.ChildProcess = Popen([Execution_Command, Executable_File] +
                                   args_list,
                                   stdin=PIPE,
                                   stdout=PIPE,
                                   bufsize=0)
     self.ModifiedOutStream = NBSR(self.ChildProcess.stdout)
Beispiel #10
0
from subprocess import Popen, PIPE
from time import sleep
import os
import sys

cwd = os.getcwd()
sys.path.append(cwd + "/plugin")
from nbstreamreader import NonBlockingStreamReader as NBSR

def start_process():
    return Popen(['gdb'], stdin=PIPE, stdout=PIPE, stderr=PIPE, shell=True, close_fds=True)

def read_stdout(nbsr, print_output=True):
    while True:
        output = nbsr.readline(0.1)
        if not output:
            break
        if print_output:
            print(output.decode("utf-8"))

process = start_process()
nbsr = NBSR(process.stdout)
read_stdout(nbsr)
process.communicate(input=b'help\n')
read_stdout(nbsr)
    global childProc, childStdout
    if not is_windows:
        childProc = Popen(['sh', 'run_lsh.sh', dataset_file, '1'],
                          stdin=PIPE,
                          stdout=PIPE,
                          bufsize=0,
                          preexec_fn=os.setsid)
    else:
        # Replace bash_path depending on your directory structure
        bash_path = 'C:\\Program Files\\Git\\bin\\bash.exe'
        childProc = Popen([bash_path, 'run_lsh.sh', dataset_file, '1'],
                          stdin=PIPE,
                          stdout=PIPE,
                          bufsize=0)

    childStdout = NBSR(childProc.stdout)

    wait_for_data('0')  # Wait for child to complete kdTree construction
    time_taken1 = time.time() - start_time

    print("[PARENT:] Construction Time Taken: %f seconds" % time_taken1)

    send_data(query_file +
              '\n')  # Send the name/path of query_file to the child
    start_time = time.time()
    send_data(str(k) + '\n')  # Send the value of k to the child
    wait_for_data('1')  # Wait for child to answer the query
    time_taken2 = time.time() - start_time

    with open("timings.txt", "a") as fp:
        fp.write("%0.6f, %0.6f, " % (time_taken1, (time_taken2 / 100)))
Beispiel #12
0
if __name__ == '__main__':
    # wait for services before starting up ...
    rospy.loginfo("Waiting for services before starting up ...")
    rospy.wait_for_service('get_obstacles')
    ObstacleDb = obstacles(0.1, 1)
    # fork and create a child subprocess of the planner
    rospy.loginfo("Running Planner with 3s startup time...")
    planner = Popen(["./planner.sh", simulation_flag],
                    stdin=PIPE,
                    stdout=PIPE,
                    bufsize=1,
                    universal_newlines=True)

    time.sleep(3)
    nbsr = NBSR(planner.stdout)
    # give time for the planner to initialize
    # the master clock for the planner
    cur_map_goal = (0, 0)
    sim_map_goal = (3.0, 4.0)
    kings_map_goal = (6.9, 7.13)

    if simulation_flag == "-simulator":
        cur_map_goal = sim_map_goal
    else:
        cur_map_goal = kings_map_goal
    if args.goalX != None and args.goalY != None:
        cur_map_goal = (float(args.goalX), float(args.goalY))

    set_new_goal(planner, nbsr, cur_map_goal[0], cur_map_goal[1])
    cur_clock = time.time()
Beispiel #13
0
def init_processes(length):
    """Send init command to all processes"""
    for i in range(1, length):
        print('{} : {}'.format(i - 1, sys.argv[i]))
        if sys.argv[i] == "human" and i < 3:
            if length == 5:
                PROCESSES.append({'type': HUMAN, 'id': i - 1})
            else:
                print(RED +
                      "To play as a human, you need a displayer executable\n" +
                      RESET)
                end(-1)
        else:
            process = Popen(sys.argv[i],
                            bufsize=0,
                            stdin=PIPE,
                            stdout=PIPE,
                            stderr=sys.stdout)
            nbsr = NBSR(process.stdout, doprint=False, idd=i - 1)
            PROCESSES.append({
                'type': COMP,
                'process': process,
                'nbsr': nbsr,
                'id': i - 1
            })

    PROCESSES[PROG_AI1]['name'] = "AI1"
    PROCESSES[PROG_AI2]['name'] = "AI2"
    PROCESSES[PROG_REF]['name'] = "REFEREE"
    if length == 5:
        PROCESSES[PROG_DIS]['name'] = "DISPLAYER"
    if not communicate(PROCESSES[PROG_REF], 'init\n', 2,
                       except_none=True) == "OK":
        print_fail(PROG_REF, "init")

    if PROCESSES[PROG_AI1]['type'] == HUMAN:
        val1 = 1
    else:
        val1 = communicate(PROCESSES[PROG_AI1], 'init\n', 2,
                           except_none=True) == "OK"

    if PROCESSES[PROG_AI2]['type'] == HUMAN:
        val2 = 1
    else:
        val2 = communicate(PROCESSES[PROG_AI2], 'init\n', 2,
                           except_none=True) == "OK"

    for i, val in enumerate([val1, val2]):
        if not val:
            print_fail(i, "init")
    check = eval_bool(val1, val2)
    if check < 2:
        end(check)

    first_human = False
    if PROCESSES[PROG_AI1]['type'] == HUMAN:
        name1 = "Human"
        first_human = True
    else:
        name1 = communicate(PROCESSES[PROG_AI1], 'name\n', 2)

    if PROCESSES[PROG_AI2]['type'] == HUMAN:
        name2 = "Human 2" if first_human else "Human"
    else:
        name2 = communicate(PROCESSES[PROG_AI2], 'name\n', 2)

    val1 = name1 is not None
    val2 = name2 is not None
    for i, val in enumerate([val1, val2]):
        if not val:
            print_fail(i, "name")
    check = eval_bool(val1, val2)
    if check < 2:
        end(check)
    PROCESSES[PROG_AI1]['name'] = name1
    PROCESSES[PROG_AI2]['name'] = name2

    if length == 5:
        if not communicate(PROCESSES[PROG_DIS], 'init\n', 2,
                           except_none=True) == "OK":
            print_fail(PROG_DIS, "init")
        if communicate(PROCESSES[PROG_DIS],
                       'names {};{}\n'.format(name1, name2),
                       2.0,
                       except_none=True) != "OK":
            print_fail(PROG_DIS, "names")
Beispiel #14
0
    '-c:v',
    'rawvideo',
    '-f',
    'rawvideo',
    '-an',
    '-sn',  # we want to disable audio processing (there is no audio)
    '-pix_fmt',
    'rgb24',
    '-s',
    '{}x{}'.format(s_height, s_width),
    'pipe:1'
]
process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
print("Command: '{}' started".format(" ".join(str(x) for x in cmd)))
fin = process.stdin
fout = NBSR(process.stdout, rgb_frame_size)

frames = []
frameBAs = []
for i in range(0, len(input_data) - 1, slice_size):
    start = i
    stop = min([i + slice_size, len(input_data)])
    slice_data = input_data[start:stop]

    #print(slice_data)
    fin.write(slice_data)

    try:
        decoded_frame = fout.read(unblocking_factor)
        #print(decoded_frame)
        if decoded_frame is not None:
Beispiel #15
0
import subprocess
import shlex
import time
from nbstreamreader import NonBlockingStreamReader as NBSR

cmd = "/home/lotus/leela-zero-0.15/src/leelaz -w /home/lotus/leela-zero-0.15/best-network --gpu 4"
args  = shlex.split(cmd)
p = subprocess.Popen(args,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,shell=False)

nbsr = NBSR(p.stdout)
colors = 'bw'
while p.poll() is None:
    output = nbsr.readline(3)
    if not output:

        color = colors[0]
        print('No more data')
        # p.stdin.write('genmove black'.encode('utf-8'))
        p.stdin.write(('genmove {}\n'.format(color)).encode('utf-8'))
        p.stdin.flush()
        colors = colors[::-1]

        # p.stdout.flush()
    print(output)
Beispiel #16
0
def main():
    #build ipcam list from config.xml
    config = 'config.xml'
    parser = XmlParser(config)
    cam_list = parser.build_cam_list()
    print 'Full List'
    for item in cam_list:
        print item.get_name()
    default = 0
    current_proc = subprocess.Popen(
        ['omxplayer', cam_list[default].get_rem_addr()],
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE)
    #input section
    cec_proc = subprocess.Popen('cec-client',
                                stdin=subprocess.PIPE,
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                shell=False)
    # wrap p.stdout with a NonBlockingStreamReader object:
    nbsr = NBSR(cec_proc.stdout)
    while True:
        output = nbsr.readline()
        # 0.1 secs to let the shell output the result
        if output:
            if (output.startswith('waiting')):
                print "Ready for input"
            if (output.startswith('TRAFFIC:')):
                sub = output.split('>>')
                if (len(sub) > 1):
                    if (sub[1].startswith(' 01:44:2')):
                        code = sub[1].split(':2')
                        print code[1]
                        char = int(code[1])
                        #while True:
                        #char = raw_input("choose camera [1 - %s ]: " % len(cam_list))
                        if char == 0:
                            subprocess.Popen(['killall', 'omxplayer.bin'])
                            break
                        if (int(char) <= len(cam_list)):
                            index = int(char) - 1
                            url = cam_list[index].get_rem_addr()
                            print url
                            #comment
                            try:
                                next_proc = subprocess.Popen(
                                    ['omxplayer', url],
                                    stdin=subprocess.PIPE,
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
                                #current_proc.communicate('p')
                                #current_proc.stdin.flush()
                                #print next_proc.stdout
                                current_proc.communicate('q')
                                temp = current_proc
                                current_proc = next_proc
                                next_proc = temp
                            except:
                                out, err = current_proc.communicate()
                                print("Error: " + err.rstrip())
                        else:
                            print(
                                "there are no cam corresponding to this number"
                            )

    sleep(0.1)
Beispiel #17
0
                                stdout=subprocess.PIPE)
        print "Java engine is running"
    return proc


def is_json(myjson):
    try:
        json_object = json.loads(myjson)
    except ValueError, e:
        return False
    return True


proc = StartEngine()
# wrap p.stdout with a NonBlockingStreamReader object:
nbsr = NBSR(proc.stdout)


@app.route("/")
def main():
    return render_template('index.html', name='index')


@app.route('/query/', methods=['GET'])
def query():
    if request.method == 'GET':
        has_result = 0
        error = 0
        q = request.args.get('q')
        print "Query: " + q
        # 1. Send the search keyword to the java application
Beispiel #18
0
    def workerThread1(self):
        """
        This is where we handle the asynchronous I/O. For example, it may be
        a 'select(  )'. One important thing to remember is that the thread has
        to yield control pretty regularly, by select or otherwise.
        """
        while self.running:
            # To simulate asynchronous I/O, we create a random number at
            # random intervals. Replace the following two lines with the real
            # thing.
            #time.sleep(rand.random() * 1.5)
            #msg = rand.random()
            #self.queue.put(msg)
            line = self._stream.readline(0.1)

            if line:
                msg = "Interruption: " + line
                print msg
                self.queue.put(msg)

    def endApplication(self):
        self.running = 0


nbsr = NBSR(sys.stdin)
rand = random.Random()
root = Tkinter.Tk()

client = ThreadedClient(root, nbsr)
root.mainloop()
Beispiel #19
0
def main(argv):
    field = initialField()
    offender = []
    defender = []

    verbose = False
    pos = None
    for arg in argv:
        if arg == '-o':
            pos = 'offender'
        elif arg == '-d':
            pos = 'defender'
        elif arg == '-v':
            verbose = True
        elif pos == 'offender':
            offender.append(arg)
        elif pos == 'defender':
            defender.append(arg)

    if len(offender) == 0 or len(defender) == 0:
        print "no args"
        return 1

    offender_proc = subprocess.Popen(offender,
                                     stdin=subprocess.PIPE,
                                     stdout=subprocess.PIPE,
                                     shell=False)
    offender_in = offender_proc.stdin
    offender_out = NBSR(offender_proc.stdout)
    offender_pid = offender_proc.pid

    defender_proc = subprocess.Popen(defender,
                                     stdin=subprocess.PIPE,
                                     stdout=subprocess.PIPE,
                                     shell=False)
    defender_in = defender_proc.stdin
    defender_out = NBSR(defender_proc.stdout)
    defender_pid = defender_proc.pid

    turn = 0
    score = 0
    while True:
        turn += 1
        if verbose:
            print '=== Turn %d (Score: %d) ===' % (turn, score)
            printField(field, sys.stdout)

        offender_in.write('game\n')
        printField(field, offender_in)
        put = offender_out.readline(2.0)
        if verbose:
            print '>> ' + put,

        field = place(field, put)
        if gameover(field):
            break
        if verbose:
            printField(field, sys.stdout)

        defender_in.write('game\n')
        printField(field, defender_in)
        direction = defender_out.readline(2.0)
        if verbose:
            print '>> ' + direction,

        moved, field, plusscore = slide(field, direction.strip())
        score += plusscore
        if not placeable(field):
            break

        if verbose:
            printField(field, sys.stdout)
        if gameover(field):
            break

    offender_in.write('quit\n')
    defender_in.write('quit\n')
    offender_proc.wait()
    defender_proc.wait()
    time.sleep(0.2)
    print 'Score: %d' % score
Beispiel #20
0
 def CreateChildProcess(self, Execution_Command, Executable_File):
     self.ChildProcess = Popen([Execution_Command, Executable_File],
                               stdin=PIPE,
                               stdout=PIPE,
                               bufsize=0)
     self.ModifiedOutStream = NBSR(self.ChildProcess.stdout)