示例#1
0
def run(target, timeout=TIMEOUT, retry=RETRY,
        preserveChildren=False, verbose=False):
    """Run a process but kill it after timeout
    @param target: the command to launch (str)
    @param timeout: timeout in seconds before start killing process (int)
    @param retry: Number of time we will try to kill the process with SIGTERM and SIGKILL (int)
    @param preserveChildren: Do we need to also kill process children ? Default is True (bool)
    @param verbose: Print what happened on standard output (bool)
    @return: 0 if everything is ok. 1 if process was killed, 2 if something goes wrong.
    """
    
    rc=0
    # Some sanity checks
    if timeout<0 or retry<1:
        print "Timeout must be a positive integer and number of retry must be greater or equal than 1"
        return 2
    if verbose:
        print "running %s" % target

    process=Popen(target, shell=True)
    endTime=time()+timeout
    while True:
        # Timeout
        if time()>endTime:
            rc=1
            if verbose:
                print "Process timeout"
            break
        # Process finish
        if process.poll() is not None:
            if verbose:
                print "Process finish before timeout"
            break
        # Wait a little before looping
        sleep(0.05)
    if process.poll() is not None:
        if verbose:
            print "process correctly finished"
    else:
        if preserveChildren:
            pids=[]
        else:
            pids=getChildrenPid(process.pid, verbose)
        pids.append(process.pid)
        for i in xrange(retry):
            for signal in (15, 9): # SIGTERM then SIGKILL
                for pid in pids:
                    if verbose:
                        print "kill %s with signal %s" % (pid, signal)
                    try:
                        os.kill(pid, signal)
                    except OSError, e:
                        if e.errno==1:
                            print "Not authorized to kill %s" % pid
                        elif e.errno==3:
                            # No such process - already dead
                            pass
                        else:
                            print "Error while killing %s:\n%s" % (pid, e)
                sleep(i)
    def testLocal(self):
        # note: ignore_zero_padding necessary until '0' padding simulation bug is resolved
        record = PacketRecord(ignore_zero_padding=True)

        # start capture
        process = Popen([CLIENT_APP, DFE_IP, DFE_NETMASK, '-l', CAPTURE_FILE], env=self.env, \
            stdout=DEV_NULL, stderr=DEV_NULL)
        self.processes.append(process)

        # send packets
        for i in range(PACKET_COUNT):
            packet = IP(dst='127.0.0.2')/ICMP()
            sendp(packet, iface=self.iface, verbose=False)
            record.add_sent(packet)

        # wait for stragglers
        time.sleep(1)

        # make sure still running
        process.poll()
        self.assertTrue(process.returncode == None)

        # stop capture
        process.terminate()
        # hack: send one more packet to make sure capture closes immediately
        sendp(IP(), iface=self.iface, verbose=False)
        process.wait()

        # verify capture CAPTURE_FILE
        for packet in rdpcap(CAPTURE_FILE):
            record.add_received(packet)
        self.assertTrue(record.verify())
    def testBasic(self):
        iface = self.tap.name
        record = PacketRecord()

        # start capture
        process = Popen([APP, iface, CAPTURE_FILE], stdout=DEV_NULL, stderr=DEV_NULL)

        # send packets
        for i in range(PACKET_COUNT):
            packet = IP(dst="www.google.com")/ICMP()
            sendp(packet, iface=iface, verbose=False)
            record.add_sent(packet)

        # wait for stragglers
        time.sleep(1)

        # stop capture
        process.terminate()
        # hack: send one more packet to make sure capture closes immediately
        sendp(IP(), iface=iface, verbose=False)
        process.poll()

        # verify capture file
        for packet in rdpcap(CAPTURE_FILE):
            record.add_received(packet)
        self.assertTrue(record.verify())
示例#4
0
文件: build.py 项目: Torxed/Scripts
def run(cmd):
	handle = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT)
	while handle.poll() is None:
		print(handle.stdout.read(1).decode('utf-8'), end='')
	print(handle.stdout.read(1).decode('utf-8'), end='') # Last byte, if there is any.
	handle.stdout.close()
	return handle.poll()
示例#5
0
    def run_and_capture(self):
        """
        Run a command and capture exceptions. This is a blocking call
        :returns: tuple of exitcode, error (or None)
        :rtype: int, str | None
        """

        subproc = Popen([self._executable,  self._command] + self._args,
                        stderr=PIPE)
        err = ''
        while subproc.poll() is None:
            line = subproc.stderr.readline().decode('utf-8')
            err += line
            sys.stderr.write(line)
            sys.stderr.flush()

        exitcode = subproc.poll()
        # We only want to catch exceptions, not other stderr messages
        # (such as "task does not exist", so we look for the 'Traceback'
        # string.  This only works for python, so we'll need to revisit
        # this in the future when we support subcommands written in other
        # languages.
        err = ('Traceback' in err and err) or None

        return exitcode, err
示例#6
0
def test_difftool(git_repo, request):
    nbdime.gitdifftool.main(['config', '--enable'])
    cmd = get_output('git config --get --local difftool.nbdime.cmd').strip()

    # pick a non-random port so we can connect later, and avoid opening a browser
    port = 62021
    cmd = cmd + ' --port=%i --browser=disabled' % port
    call(['git', 'config', 'difftool.nbdime.cmd', cmd])

    # avoid global diff driver config from disabling difftool:
    with open('.gitattributes', 'w') as f:
        f.write('*.ipynb\tdiff=notnbdime')

    p = Popen(['git', 'difftool', '--tool=nbdime', 'base'])
    def _term():
        try:
            p.terminate()
        except OSError:
            pass
    request.addfinalizer(_term)
    
    # 3 is the number of notebooks in this diff
    url = 'http://127.0.0.1:%i' % port
    for i in range(3):
        _wait_up(url, check=lambda : p.poll() is None)
        # server started
        r = requests.get(url + '/difftool')
        r.raise_for_status()
        # close it
        r = requests.post(url + '/api/closetool', headers={'exit_code': '0'})
        r.raise_for_status()
        time.sleep(0.25)
    # wait for exit
    p.wait()
    assert p.poll() == 0
示例#7
0
    def _popen(self, command, timeout, timeout_msg, rc_non_zero_msg, common_msg=""):
        """ Runs a command in background and returns its return_code, stdout and stderr.
        stdout and stderr will be None if return code = 0
        """
        stdout, stderr = None, None

        # Run the command
        p = Popen(command, stdout=PIPE, stderr=PIPE)

        # Sleep as long as requested and poll for results
        sleep(timeout)
        p.poll()

        if p.returncode is None:
            msg = timeout_msg + common_msg + "command:[{}]".format(command)
            raise Exception(msg.format(timeout))
        else:
            if p.returncode != 0:
                stdout, stderr = p.communicate()
                msg = (
                    rc_non_zero_msg
                    + common_msg
                    + "command:[{}], return code:[{}], stdout:[{}], stderr:[{}] ".format(
                        command, p.returncode, stdout, stderr
                    )
                )
                raise Exception(msg)

        return p.returncode
示例#8
0
    def start(self):
        """Start the process."""
        import shlex
        from subprocess import Popen

        if self.process:
            raise RuntimeError("Process already started.")
        if self.host and self.network_ping():
            raise RuntimeError("A process is already running on port %s" %
                               self.port)

        if isinstance(self.cmd, basestring):
            cmd = shlex.split(self.cmd)
        else:
            cmd = self.cmd
        self.null = open('/dev/null', 'w')
        process = Popen(cmd, stdout=self.null, stderr=self.null, close_fds=True)

        if not self.host:
            time.sleep(0.35)
            if process.poll():
                output = process.communicate()[0]
                raise RuntimeError("Did not start server!  Woe!\n" + output)
            self.process = process
            return

        start = time.time()
        while process.poll() is None and time.time() - start < 15:
            if self.network_ping():
                break
        else:
            output = process.communicate()[0]
            raise RuntimeError("Did not start server!  Woe!\n" + output)
        self.process = process
示例#9
0
文件: inetd-test.py 项目: blanu/Dust
class Inetd:
  def __init__(self, inq, outq):
    self.inq=inq
    self.outq=outq

  def start(self):
    self.proc=Popen(['fossil', 'http', '/home/blanu/fossil/'], stdin=PIPE, stdout=PIPE)
#    self.proc=Popen(['fossil', 'help'], stdin=PIPE, stdout=PIPE)

    t=Thread(target=self.processIn)
    t.setDaemon(True)
    t.start()

    t2=Thread(target=self.processOut)
#    t2.setDaemon(True)
    t2.start()

  def processIn(self):
    self.proc.poll()
    while not self.proc.returncode:
      data=self.inq.get()
      print('inetd -> '+str(data))
      self.proc.stdin.write(data)
      self.proc.stdin.flush()
      self.proc.poll()

  def processOut(self):
    print('waiting to finish')
#    self.proc.wait()
    print('finished')
    print('waiting to read from inetd')
    data=self.proc.stdout.read()
    print('inetd <- '+str(data))
    self.outq.put(data)
示例#10
0
def yes_proc(args, yes="yes"):
    proc = Popen(args, stdin=PIPE)
    while proc.returncode is None:
        proc.communicate(yes)
        proc.poll()

    return proc.returncode == 0
示例#11
0
def wait_process_finish(scan, profile_fname):
    '''
    Start w3af process in new process, and wait while it terminate
    '''
    process = Popen([settings.W3AF_RUN,
                    '--no-update', '-P',
                    profile_fname],
                    stdout=PIPE,
                    stderr=PIPE)
    scan.pid = process.pid
    scan.save()
    while process.returncode is None:
        scan.last_updated = datetime.today()
        scan.save()
        sleep(W3AF_POLL_PERIOD) # wail 
        process.poll() # get process status
    scan.set_task_status_free()
    finish_time = datetime.now()
    scan.finish = finish_time
    scan.save()
    target = scan.scan_task.target
    target.last_scan = finish_time
    target.save()
    logger.info('w3af Process return code %s' % process.returncode)
    return process.returncode
 def start(self, timeout = 20):
     if self.is_running():
         raise Exception('%s is already running' % self.name)
     if not self.run_cmd:
         raise Exception('No starting command registered for %s' % self.name)
     if type(self.run_cmd) is types.FunctionType:
         self.run_cmd()
         return
     with tempfile.TemporaryFile() as stdout_file, tempfile.TemporaryFile() as stderr_file:
         proc = Popen(shlex.split('%s -p %s' % (self.run_cmd, self.port)), cwd = self.dir, close_fds = True,
                      stdout = stdout_file, stderr = stderr_file)
         if timeout > 0:
             poll_rate = 0.1
             for i in range(int(timeout/poll_rate)):
                 if self.is_running():
                     break
                 sleep(poll_rate)
                 if bool(proc.poll()): # process ended with error
                     stdout_file.seek(0)
                     stderr_file.seek(0)
                     raise Exception('Run of %s ended unexpectfully: %s' % (self.name, [proc.returncode, stdout_file.read().decode(errors = 'replace'), stderr_file.read().decode(errors = 'replace')]))
                 elif proc.poll() == 0: # process runs other process, and ended
                     break
         if self.is_running():
             if self.check_connectivity():
                 return True
             raise Exception('Daemon process is running, but no connectivity')
         raise Exception('%s failed to run.' % self.name)
示例#13
0
class TestServer(unittest.TestCase):
    server = 'WSGIRefServer'
    port = 12643

    def setUp(self):
        # Start servertest.py in a subprocess
        cmd = [sys.executable, serverscript, self.server, str(self.port)]
        cmd += sys.argv[1:] # pass cmdline arguments to subprocesses
        self.p = Popen(cmd, stdout=PIPE, stderr=PIPE)
        # Wait for the socket to accept connections
        for i in xrange(100):
            time.sleep(0.1)
            # Check if the process has died for some reason
            if self.p.poll() != None: break
            if ping('127.0.0.1', self.port): break

    def tearDown(self):
        while self.p.poll() is None:
            os.kill(self.p.pid, signal.SIGINT)
            time.sleep(0.1)
            if self.p.poll() is None:
                os.kill(self.p.pid, signal.SIGTERM)
        for stream in (self.p.stdout, self.p.stderr):
            for line in stream:
                if tob('Warning') in line \
                or tob('Error') in line:
                    print line.strip().decode('utf8')

    def fetch(self, url):
        try:
            return urllib2.urlopen('http://127.0.0.1:%d/%s' % (self.port, url)).read()
        except Exception, e:
            return repr(e)
示例#14
0
class Engine:
    def __init__(self, cmdline):
        self.proc = Popen(cmdline, stdin = PIPE, stdout = PIPE)
        self.proc_com = _ProcCom(self.proc)
        self.proc_com.start()

    def send(self, msg):
        self.proc.stdin.write(msg)
        self.proc.stdin.flush()

    def readline(self, timeout=None):
        if self.proc.poll():
            return ""
        try:
            msg = self.proc_com.outq.get(timeout=timeout)
        except Empty:
            raise socket.timeout()
        return msg

    def cleanup(self):
        self.proc_com.stop.set()
        if self.proc.poll() is None:
            if sys.platform == 'win32':
                import ctypes
                handle = int(self.proc._handle)
                ctypes.windll.kernel32.TerminateProcess(handle, 0)
            else:
                os.kill(self.proc.pid, signal.SIGTERM)
示例#15
0
    def worker(self, cmd_q, res_q):
        while True:
            name, cmd = cmd_q.get(True)

            self.log.debug("External : launch %s" % cmd)

            try:
                proc = Popen(
                    cmd,
                    stdin=None, stdout=PIPE, stderr=STDOUT, close_fds=True)

                output = ""
                while True:
                    out, err = proc.communicate()
                    proc.poll()
                    output += out.decode('utf-8')
                    if proc.returncode is not None:
                        break

            except:
                self.log.debug(traceback.format_exc())

            # Truncate multi-line output
            try:
                output = output[:output.index("\n")]
            except:
                pass

            res_q.put_nowait(
                (name, proc.returncode, output, int(time.time())))
            cmd_q.task_done()
示例#16
0
def setup_kernel(cmd):
    """start an embedded kernel in a subprocess, and wait for it to be ready

    Returns
    -------
    kernel_manager: connected KernelManager instance
    """
    kernel = Popen([sys.executable, "-c", cmd], stdout=PIPE, stderr=PIPE, env=env)
    connection_file = os.path.join(IPYTHONDIR, "profile_default", "security", "kernel-%i.json" % kernel.pid)
    # wait for connection file to exist, timeout after 5s
    tic = time.time()
    while not os.path.exists(connection_file) and kernel.poll() is None and time.time() < tic + SETUP_TIMEOUT:
        time.sleep(0.1)

    if kernel.poll() is not None:
        o, e = kernel.communicate()
        e = py3compat.cast_unicode(e)
        raise IOError("Kernel failed to start:\n%s" % e)

    if not os.path.exists(connection_file):
        if kernel.poll() is None:
            kernel.terminate()
        raise IOError("Connection file %r never arrived" % connection_file)

    client = BlockingKernelClient(connection_file=connection_file)
    client.load_connection_file()
    client.start_channels()

    try:
        yield client
    finally:
        client.stop_channels()
        kernel.terminate()
 def compile(self, filename):
     if (self.debug_output == 1):
         print("compile " + self.processor)
     else:
         chemin = os.path.dirname(filename)
         fichier = open(sys.path[0] + "/tmp/stdout", 'w+')
         sortie = Popen([sys.path[0] + "/tools/bin/sdcc",
                     "-mpic16",
                     "--denable-peeps",
                     "--obanksel=9",
                     "--opt-code-size",
                     "--optimize-cmp",
                     "--optimize-df",
                     "-p" + self.processor,                        
                     "-I" + sys.path[0] + "/include",
                     "-I" + chemin + "/",
                     "-c",
                     "-c",
                     "-o" + sys.path[0] + "/source/main.o",
                     sys.path[0] + "/source/main.c"],
                     stdout=fichier, stderr=STDOUT)
         sortie.communicate()
         if sortie.poll()!=0:
             fichier.seek(0)
             self.displaymsg(fichier.read(), 0)
         fichier.seek(0)
         line=fichier.readline()
         if line.find("error")!=-1:
             number=line[line.find(":")+1:line.find("error")-2]
             self.editor.highlightline(int(number)-1,'pink')
             self.displaymsg("error line"+" "+number+"\n",1)
             self.displaymsg(line[line.find("error")+10:len(line)],0)
         fichier.close()
         return sortie.poll()
class CMatProcess:
    def __init__(self, processPath='./cmatprocess/cmatprocess', nCores=4):
        assert processPath is not None

        self.cmd = [processPath, str(nCores)]

        self.p = Popen(self.cmd, stdin=PIPE, stdout=PIPE,
                       stderr=PIPE, bufsize=0)

        def exitHandler():
            if self.p.poll() is None:
                self.p.kill()
        atexit.register(exitHandler)

    def processPaths(self, imgPaths, f):
        rc = self.p.poll()
        if rc is not None and rc != 0:
            raise Exception("Error from process!")

        self.p.stdin.write(f + ' ' + ' '.join(imgPaths) + '\n')
        try:
            n = int(self.p.stdout.readline())
            result = []
            for i in range(n):
                fileLocation = self.p.stdout.readline().strip()
                if len(fileLocation) > 3:
                    result.append(cv2.imread(fileLocation))

            return result
        except Exception as e:
            self.p.kill()
            stdout, stderr = self.p.communicate()
            print("Error from process output: " + stdout + '\n' + stderr)
            sys.exit(-1)
示例#19
0
 def run(self):
     try:
         if osflag:
             proc=Popen(self.cmd,shell=False,stdin=None,stdout=PIPE,\
                 stderr=STDOUT,bufsize=0)
         else:
             from subprocess import STARTUPINFO
             si=STARTUPINFO()
             si.dwFlags|=1
             si.wShowWindow=0
             proc=Popen(self.cmd,shell=False,stdin=None,stdout=PIPE,\
                 stderr=STDOUT,bufsize=0,startupinfo=si)
         while 1:
             if self.stop_flag:
                 if osflag: proc.send_signal(signal.SIGKILL)
                 else: proc.kill()
                 break
             if osflag:
                 if proc.stdout in select.select([proc.stdout],[],[],1)[0]:
                     line=proc.stdout.readline()
                 else: line=' \n'
             else: line=proc.stdout.readline()
             if not len(line): break
             else:
                 if count(line,'ttl') or count(line,'TTL'): self.retries=0
                 else: self.retries=self.retries+1
                 line=' '
             sleep(0.5)
         proc.poll()
     except: pass
示例#20
0
def run_tsmuxer_2(msg, argv1, argv2):
    out = StringIO.StringIO()
    argv = ['tsMuxeR', argv1, argv2]
    p = Popen(argv, stdout=PIPE, stderr=PIPE)
    write("%s ...\n" % msg)
    while True:
        line = p.stdout.readline()
        if line == '':
            if p.poll() is not None:
                break   #reached final line of output
            else:
                time.sleep(0.01) # sleep 10 milliseconds
        else:
            out.write(line)
            progress = extract_progress(line)
            if progress is not None:
                write("\r%5.1f%% completed" % progress)
    
    write("\n")

    try:
        assert p.poll() == 0
        return True
    except AssertionError:
        print "ERROR: Muxing failed"
        print "Args:", argv
        out = out.read()
        print "STDOUT:"
        print out
        err = p.stderr.read()
        print "STDERR:"
        print err
        return False
示例#21
0
class RunServer(object):

    def __init__(self, instance_name, port):
        self.instance_name = instance_name
        self.port = port
        self.lan_ip = get_lan_ip()
        self.process = None
        self.out = None

    def start(self):
        self.stop()
        cmd = [sys.executable, 'manage_%s.py' % self.instance_name,
               'runserver', '--noreload', '--traceback', '0.0.0.0:%d' % self.port]
        self.process = Popen(cmd)
        sleep(3.0)
        if self.process.poll() is not None:
            self.stop()
            raise RunException(ugettext("Error to start!"))
        self.open_url()

    def open_url(self):
        webbrowser.open_new("http://%(ip)s:%(port)d" %
                            {'ip': self.lan_ip, 'port': self.port})

    def stop(self):
        if self.is_running():
            self.process.terminate()
        self.process = None
        self.out = None

    def is_running(self):
        return (self.process is not None) and (self.process.poll() is None)
示例#22
0
class ExecuteHook(BaseHook):
    """
    Hook that executes an arbitary command in the setup phase.
    If the command is still running during teardown, it will
    be terminated.
    """
    def __init__(self, args):
        """
        :param args: sequence of program arguments,
                     see :class:`subprocess.Popen` for details
        :type args: string or sequence
        """
        super(ExecuteHook, self).__init__()
        self.args = args
        self.proc = None

    def setup(self):
        self.proc = Popen(shlex.split(self.args) if
                isinstance(self.args, str) else self.args)

    def teardown(self):
        self.proc.poll()
        if self.proc.returncode is None:
            self.proc.terminate()
            self.proc.wait()
示例#23
0
def _launch_kernel(cmd):
    """start an embedded kernel in a subprocess, and wait for it to be ready
    
    Returns
    -------
    kernel, kernel_manager: Popen instance and connected KernelManager
    """
    kernel = Popen([sys.executable, '-c', cmd], stdout=PIPE, stderr=PIPE, env=env)
    connection_file = os.path.join(IPYTHONDIR,
                                    'profile_default',
                                    'security',
                                    'kernel-%i.json' % kernel.pid
    )
    # wait for connection file to exist, timeout after 5s
    tic = time.time()
    while not os.path.exists(connection_file) and kernel.poll() is None and time.time() < tic + 5:
        time.sleep(0.1)
    
    if not os.path.exists(connection_file):
        if kernel.poll() is None:
            kernel.terminate()
        raise IOError("Connection file %r never arrived" % connection_file)
    
    if kernel.poll() is not None:
        raise IOError("Kernel failed to start")
    
    km = BlockingKernelManager(connection_file=connection_file)
    km.load_connection_file()
    km.start_channels()
    
    return kernel, km
    def upload_using_curl(self, source_directory, target_directory):
        logging.debug("Curl upload!")
        import os

        filesToUpload = os.listdir(source_directory)
        for file in filesToUpload:
            logging.warn(source_directory)
            logging.warn(file)
            filePath = os.path.join(source_directory, file)
            curlcommand = "curl --ftp-create-dirs -T {filepath} --keepalive-time 5 --user {user}:{password} ftp://{host}{remotedir}/".format(
                user=self.user,
                password=self.password,
                port=self.port,
                host=self.hostname,
                remotedir=target_directory,
                filepath=filePath,
            )
            logging.debug(curlcommand)
            p = Popen(curlcommand)
            stdout, stderr = p.communicate()
            logging.debug(stdout)
            p.poll()
            curlReturnValue = p.returncode
            if curlReturnValue != 0:
                logging.error("CURL has encurred into an error! the program execution will stop!")
                raise Exception("CURL returned invalid status code")
示例#25
0
  def exec_and_wait(self, cmd, timelife = 10):
    """
    exec_and_wait is syncronous with a timelife given by
    parameter whether is reached the command request is returning and error.
    retruncode is an Operating System err code, != 0 are error codes
    """

    proc = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, close_fds=True)
    t_nought = time.time()
    seconds_passed = 0
    self.pid = proc.pid
    self.stderr = proc.stderr
    self.stdout = proc.stdout.read().rstrip('\n')
    self.returncode = proc.poll()
    while(self.returncode != 0 and seconds_passed < timelife):
      seconds_passed = time.time() - t_nought
      self.returncode = proc.poll()

    if seconds_passed >= timelife:
      self.returncode = 1
      self.stdout = "Timelife expired, connection aborted"
      return

    self.returncode = 0
    return
示例#26
0
def local_popen( f, cmdline ):
   if os.name != 'nt':
      cmdline="./" + cmdline

   if execution==0:
      print cmdline
   else:
      p=Popen( cmdline, shell=True, stdout=PIPE, stderr=STDOUT )

      r=p.poll()
      while r == None:
         r=p.poll()
      pipe=p.stdout

      if r != 0:
         print "---- TESTING " + cmdline.split()[3] + "... FAILED(" + str(p.returncode) +") !"
         for line in pipe.readlines():
            f.write(str(line))
      else:
         found=0
         for line in pipe.readlines():
            f.write(str(line))
            if "TESTING" in line :
               found = 1
               print line,
         if found == 0:
            print cmdline.split()[0] + " " + cmdline.split()[3] + ": FAILED(Unexpected error)"
            
   f.flush();
   return 0
示例#27
0
class Player:
    def __init__(self, name, cmd):
        self.name = name
        self.forts = set()
        self.marches = set()
        args = cmd.split(' ')
        self.process = Popen(list(args) + [name], stdin=PIPE, stdout=PIPE,
                             universal_newlines=True)

    def capture(self, fort):
        if fort.owner:
            fort.owner.forts.remove(fort)
        self.forts.add(fort)
        fort.owner = self

    def is_defeated(self):
        return (not self.forts) and (not self.marches)

    def send_state(self):
        if not self.process.poll():
            self.process.stdin.write(show_visible(self.forts))
            self.process.stdin.write('\n')
            self.process.stdin.flush()

    def read_commands(self, game):
        if not self.process.poll():
            try:
                read_commands(game, self, self.process.stdout)
            except StopIteration:
                self.process.kill()
示例#28
0
def main(args=sys.argv[1:]):
    parser = argparse.ArgumentParser(description="Adapt socket communication.")
    parser.add_argument("--server")
    parser.add_argument("--port", type=int)
    parser.add_argument("--legacy", nargs=2)
    config = parser.parse_args(args)

    if config.legacy:
        address = (config.legacy[0], int(config.legacy[1]))
    else:
        address = (config.server, config.port)
    sock = socket.socket()
    sock.connect(address)

    proc = Popen("simple_engine", stdin=PIPE, stdout=PIPE,
                 universal_newlines=True)
    com = _ProcCom(proc, sock)
    com.start()

    while proc.poll() is None:
        msg = sock.recv(4096)
        if len(msg) == 0:
            break
        proc.stdin.write(msg)
        proc.stdin.flush()
    if proc.poll() is None:
        proc.stdin.write("quit\n")
        proc.stdin.flush()
    com.stop.set()
    sock.close()
示例#29
0
文件: xpipe.py 项目: p-static/xpipe
class GraphNode:
	def __init__(self, name, command):
		self.name = name
		self.command = command
		self.process = None
		self.stdin = None
		self.stdout = None
		self.outputs = []
	
	def execute(self):
		if self.command is not None:
			self.process = Popen(self.command, shell=True, stdin=PIPE, stdout=PIPE, stderr=None)
			make_nonblocking(self.process.stdout.fileno())
			make_nonblocking(self.process.stdin.fileno())
			self.stdin = GraphNodeStream(self, self.process.stdin, 'stdin')
			self.stdout = GraphNodeStream(self, self.process.stdout, 'stdout')
	
	# Returns False iff this node will never produce more data
	def is_live(self):
		if self.process is not None:
			self.process.poll()
		return self.command is None or (self.process is not None and self.process.returncode is None)
	
	def is_readable(self):
		return self.stdout.is_live()
	
	def is_writable(self):
		return self.stdin.is_live()
	
	def __repr__(self):
		if self.command is None:
			return "(" + self.name + ")"
		return "(" + self.name + ": " + self.command + ")"
示例#30
0
def run():
    args = _parse_args()

    try:
        tornado = Popen(['python', '../static-server.py'])
        node = Popen(['node', 'build/server/server.js'])

        sleep(1)

        for url, page_name in PAGE_LIST:
            out_file = os.path.join(BUILD_DIR, page_name + '.html')
            # useless, since template is cached by tornado
            os.unlink(out_file)

            url = TORNADO_SERVER[:-1] + url
            phantom = Popen(['phantomjs', 'ph.js', url], stdout=PIPE)
            styles = phantom.stdout.readline().rstrip()
            load_css_func = _process_js_func(LOAD_CSS_FUNC)
            template = TEMPLATE.format(style=styles, load_css_func=load_css_func)

            with open(out_file, 'w') as f:
                f.write(template)
                print("out file:", out_file)
            phantom.communicate()
    finally:
        try:
            if tornado.poll() is None:
                tornado.terminate()
        except Exception:
            pass
        try:
            if node.poll() is None:
                node.terminate()
        except Exception:
            pass