def test_lowres(): with Display(): p = EasyProcess([python, "-m", "pyvirtualdisplay.examples.lowres"]).start() sleep(1) assert p.is_alive() # p.stop() kill_process_tree(p)
def main(): pls = [] try: os.chdir("gen") for cmd, grab, bg in commands: with SmartDisplay() as disp: logging.info("======== cmd: %s", cmd) fname_base = cmd.replace(" ", "_") fname = fname_base + ".txt" # logging.info("cmd: %s", cmd) print("file name: %s" % fname) with open(fname, "w") as f: f.write("$ " + cmd) if bg: p = EasyProcess(cmd).start() else: p = EasyProcess(cmd).call() f.write(p.stdout) f.write(p.stderr) pls += [p] if grab: png = fname_base + ".png" sleep(1) img = disp.waitgrab(timeout=9) logging.info("saving %s", png) img.save(png) finally: os.chdir("..") for p in pls: p.stop() embedme = EasyProcess(["npx", "embedme", "../README.md"]) embedme.call() print(embedme.stdout) assert embedme.return_code == 0 assert not "but file does not exist" in embedme.stdout
def test_time_cli2(self): p = EasyProcess([ python, '-c', "import logging;logging.basicConfig(level=logging.DEBUG);from easyprocess import EasyProcess;EasyProcess('sleep 5').call(timeout=0.5)" ]) p.call() eq_(p.return_code, 0)
def test_timeout_out(self): p = EasyProcess( [python, '-c', "import time;print( 'start');time.sleep(5);print( 'end')"]).call(timeout=1) eq_(p.is_alive(), False) eq_(p.timeout_happened, True) ok_(p.return_code < 0) eq_(p.stdout, '')
def __init__(self, use_xauth=False, check_startup=False, randomizer=None): with mutex: self.display = self.search_for_display(randomizer=randomizer) while self.display in USED_DISPLAY_NR_LIST: self.display += 1 USED_DISPLAY_NR_LIST.append(self.display) if use_xauth and not xauth.is_installed(): raise xauth.NotFoundError() self.use_xauth = use_xauth self._old_xauth = None self._xauth_filename = None self.check_startup = check_startup if check_startup and not fcntl: self.check_startup = False log.warning( "fcntl module can't be imported, 'check_startup' parameter has been disabled" ) log.warning("fnctl module does not exist on Windows") if self.check_startup: rp, wp = os.pipe() fcntl.fcntl(rp, fcntl.F_SETFD, fcntl.FD_CLOEXEC) # to properly allow to inherit fds to subprocess on # python 3.2+ the easyprocess needs small fix.. fcntl.fcntl(wp, fcntl.F_SETFD, 0) self.check_startup_fd = wp self._check_startup_fd = rp EasyProcess.__init__(self, self._cmd)
def test_1_cli(): cmd = [python, example1_py, "5"] p = EasyProcess(cmd).call() ported_eq(p.return_code, 0) ported_eq(p.stdout, "") ported_eq(p.stderr, "") cmd = [python, example1_py, "5", "--two", "7", "--debug"] p = EasyProcess(cmd).call() ported_eq(p.return_code, 0) ported_eq(p.stdout, "") ported_eq(p.stderr, "") cmd = [python, example1_py, "5", "--three", "-t", "2", "--debug"] p = EasyProcess(cmd).call() ported_eq(p.return_code, 0) ported_eq(p.stdout, "") ported_eq(p.stderr, "") cmd = [python, example1_py, "5", "-t", "x"] p = EasyProcess(cmd).call() ported_eq(p.return_code > 0, 1) ported_eq(p.stdout, "") ported_eq(p.stderr != "", 1) cmd = [python, example1_py, "-t", "1", "5", "--debug"] p = EasyProcess(cmd).call() ported_eq(p.return_code, 0) ported_eq(p.stdout, "") ported_eq(p.stderr, "")
def prog_shot(cmd, f, wait, timeout, screen_size, visible, bgcolor, cwd=None): '''start process in headless X and create screenshot after 'wait' sec. Repeats screenshot until it is not empty if 'repeat_if_empty'=True. wait: wait at least N seconds after first window is displayed, it can be used to skip splash screen :param enable_crop: True -> crop screenshot :param wait: int ''' disp = SmartDisplay(visible=visible, size=screen_size, bgcolor=bgcolor) disp.pyscreenshot_backend = None disp.pyscreenshot_childprocess = True proc = EasyProcess(cmd, cwd=cwd) def func(): try: img = disp.waitgrab(timeout=timeout) except DisplayTimeoutError as e: raise DisplayTimeoutError(str(e) + ' ' + str(proc)) if wait: proc.sleep(wait) img = disp.grab() return img img = disp.wrap(proc.wrap(func))() if img: img.save(f) return (proc.stdout, proc.stderr)
def getRainTicks(): global ticks global temperature os.system('rm -Rf '+json_rain_sensor) time.sleep(0.5) cmd = "rtl_433 -R 37 -E -F json:"+json_rain_sensor try: stdout=Proc(cmd).call(timeout=120).stdout time.sleep(0.5) with open(json_rain_sensor) as f: data = json.loads(f.readline()) if "temperature_C" in data: temperature = float(data["temperature_C"]) if "rain" in data: ticks = int(data["rain"]) except: print(CRED+'[NOK] rtl_433 timed out'+CEND) from easyprocess import EasyProcess s=EasyProcess("lsusb").call().stdout for line in s.splitlines(): if line.find('Realtek')!=-1: cmd = "sudo usb_reset /dev/bus/usb/"+line[4:7]+"/"+line[15:18] stdout=Proc(cmd).call().stdout print(cmd + ' ' +stdout) return ticks, temperature
def init(): global refimgpath if not refimgpath: d = tempfile.mkdtemp(prefix="fillscreen") d = Path(d) atexit.register(d.rmtree) refimgpath = d / "ref.png" if not platform_is_win(): # TODO: win image viewer im = generate_image() im.save(refimgpath) cmd = [ "pqiv", "--fullscreen", "--hide-info-box", "--disable-scaling", refimgpath, ] proc = EasyProcess(cmd).start() atexit.register(proc.stop) print(refimgpath) sleep(5) # TODO: check image displayed if not proc.is_alive(): raise FillscreenError("pqiv stopped: %s" % proc) # if the OS has color correction # then the screenshot has slighly different color than the original image # TODO: color correction: linux? win? if platform_is_win() or platform_is_osx(): refimgpath = refimgpath + ".pil.png" im = pyscreenshot.grab(backend="pil") im.save(refimgpath) log.debug("%s saved", refimgpath) return refimgpath
def display_size(): if platform_is_osx(): from Quartz import CGDisplayBounds from Quartz import CGMainDisplayID mainMonitor = CGDisplayBounds(CGMainDisplayID()) return int(mainMonitor.size.width), int(mainMonitor.size.height) if platform_is_win(): from win32api import GetSystemMetrics return int(GetSystemMetrics(0)), int(GetSystemMetrics(1)) if platform_is_linux(): # http://www.cyberciti.biz/faq/how-do-i-find-out-screen-resolution-of-my-linux-desktop/ # xdpyinfo | grep 'dimensions:' screen_width, screen_height = 0, 0 xdpyinfo = EasyProcess("xdpyinfo") xdpyinfo.enable_stdout_log = False if xdpyinfo.call().return_code != 0: raise ValueError("xdpyinfo error: %s" % xdpyinfo) for x in xdpyinfo.stdout.splitlines(): if "dimensions:" in x: screen_width, screen_height = map(int, x.strip().split()[1].split("x")) return screen_width, screen_height
def test_help(): cmd = [python, "-m", "pyunpack.cli", "--help"] h = EasyProcess(cmd).call().stdout.strip() h = h.replace("\r", "") # for win print(help) print(h) assert h == help
def test_1_cli(): cmd = [python, example1_py, "5"] p = EasyProcess(cmd).call() assert p.return_code == 0 assert p.stdout == "" assert p.stderr == "" cmd = [python, example1_py, "5", "--two", "7", "--debug"] p = EasyProcess(cmd).call() assert p.return_code == 0 assert p.stdout == "" assert p.stderr == "" cmd = [python, example1_py, "5", "--three", "-t", "2", "--debug"] p = EasyProcess(cmd).call() assert p.return_code == 0 assert p.stdout == "" assert p.stderr == "" cmd = [python, example1_py, "5", "-t", "x"] p = EasyProcess(cmd).call() assert p.return_code > 0 assert p.stdout == "" assert p.stderr != "" cmd = [python, example1_py, "-t", "1", "5", "--debug"] p = EasyProcess(cmd).call() assert p.return_code == 0 assert p.stdout == "" assert p.stderr == ""
def prog_shot(cmd, f, wait, timeout, screen_size, visible, bgcolor, cwd=None): '''start process in headless X and create screenshot after 'wait' sec. Repeats screenshot until it is not empty if 'repeat_if_empty'=True. wait: wait at least N seconds after first window is displayed, it can be used to skip splash screen :param enable_crop: True -> crop screenshot :param wait: int ''' disp = SmartDisplay(visible=visible, size=screen_size, bgcolor=bgcolor) disp.pyscreenshot_backend = None disp.pyscreenshot_childprocess = True proc = EasyProcess(cmd, cwd=cwd) def func(): try: img = disp.waitgrab(timeout=timeout) except DisplayTimeoutError as e: raise DisplayTimeoutError(str(e) + ' ' + str(proc)) if wait: proc.sleep(wait) img = disp.grab() return img img = disp.wrap(proc.wrap(func))() if img: img.save(f) return (proc.stdout, proc.stderr)
def test_nested(): with Display(): p = EasyProcess([python, "-m", "pyvirtualdisplay.examples.nested"]).start() sleep(1) assert p.is_alive() p.stop()
def main(): gendir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "gen") logging.info("gendir: %s", gendir) os.makedirs(gendir, exist_ok=True) empty_dir(gendir) try: os.chdir("gen") for cmd in commands: logging.info("cmd: %s", cmd) fname_base = cmd.replace(" ", "_") fname = fname_base + ".txt" logging.info("cmd: %s", cmd) print("file name: %s" % fname) with open(fname, "w") as f: f.write("$ " + cmd + "\n") p = EasyProcess(cmd).call() f.write(p.stderr) if p.stderr and p.stdout: f.write("\n") f.write(p.stdout) finally: os.chdir("..") embedme = EasyProcess(["embedme", "../README.md"]) embedme.call() print(embedme.stdout) assert embedme.return_code == 0 assert "but file does not exist" not in embedme.stdout
def test_slowshot_wrap(self): disp = SmartDisplay(visible=0) py = path(__file__).parent / ('slowgui.py') proc = EasyProcess('python ' + py) f = disp.wrap(proc.wrap(disp.waitgrab)) img = f() eq_(img is not None, True)
def test_alive(self): eq_(EasyProcess('ping 127.0.0.1 -c 2').is_alive(), False) eq_(EasyProcess('ping 127.0.0.1 -c 2').start().is_alive(), True) eq_( EasyProcess('ping 127.0.0.1 -c 2').start().stop().is_alive(), False) eq_(EasyProcess('ping 127.0.0.1 -c 2').call().is_alive(), False)
def start(self): ''' start display :rtype: self ''' if self.use_xauth: self._setup_xauth() EasyProcess.start(self) # https://github.com/ponty/PyVirtualDisplay/issues/2 # https://github.com/ponty/PyVirtualDisplay/issues/14 self.old_display_var = os.environ.get('DISPLAY', None) self.redirect_display(True) # wait until X server is active start_time = time.time() if self.check_startup: rp = self._check_startup_fd display_check = None rlist, wlist, xlist = select.select((rp,), (), (), X_START_TIMEOUT) if rlist: display_check = os.read(rp, 10).rstrip() else: msg = 'No display number returned by X server' raise XStartTimeoutError(msg) dnbs = str(self.display) if bytes != str: dnbs = bytes(dnbs, 'ascii') if display_check != dnbs: msg = 'Display number "%s" not returned by X server' + str(display_check) raise XStartTimeoutError(msg % self.display) d = self.new_display_var ok = False while True: try: exit_code = EasyProcess('xdpyinfo').call().return_code except EasyProcessError: log.warn('xdpyinfo was not found, X start can not be checked! Please install xdpyinfo!') time.sleep(X_START_WAIT) # old method ok = True break if exit_code != 0: pass else: log.info('Successfully started X with display "%s".', d) ok = True break if time.time() - start_time >= X_START_TIMEOUT: break time.sleep(X_START_TIME_STEP) if not ok: msg = 'Failed to start X on display "%s" (xdpyinfo check failed).' raise XStartTimeoutError(msg % d) return self
def test_slowshot(): disp = SmartDisplay(visible=False).start() py = Path(__file__).parent / ("slowgui.py") proc = EasyProcess([python, py]).start() img = disp.waitgrab() proc.stop() disp.stop() assert img is not None
def test_timeout_out(): p = EasyProcess([ python, "-c", "import time;print( 'start');time.sleep(5);print( 'end')" ]).call(timeout=1) assert p.is_alive() is False assert p.timeout_happened assert p.return_code != 0 assert p.stdout == ""
def test_time_cli2(): p = EasyProcess([ python, "-c", "import logging;logging.basicConfig(level=logging.DEBUG);from easyprocess import EasyProcess;EasyProcess('sleep 5').call(timeout=0.5)", ]) p.call() assert p.return_code == 0
def test_check(self): eq_(EasyProcess('ls -la').check().return_code, 0) eq_(EasyProcess(['ls', '-la']).check().return_code, 0) self.assertRaises(EasyProcessError, lambda: EasyProcess('xxxxx').check()) self.assertRaises(EasyProcessError, lambda: EasyProcess('sh -c xxxxx').check())
def test_slowshot(self): disp = SmartDisplay(visible=0).start() py = path(__file__).parent / ('slowgui.py') proc = EasyProcess('python ' + py).start() img = disp.waitgrab() proc.stop() disp.stop() eq_(img is not None, True)
def _backend_ref(backend): with EasyProcess('xlogo'): with EasyProcess('xmessage -center "%s"' % long_txt): time.sleep(2) for bbox in bbox_ls: print('bbox: {}'.format(bbox)) print('backend: %s' % backend) check_ref(backend, bbox)
def AddDisplay(): global disps, easyprocs, sshconns numdispwins = len(disps) if numdispwins > 0: numdispwins += 1 # this hack, so we have first top left, second bottom left, third bottom right mypos = ((numdispwins % 2) * wdeskhalf, get_bit(numdispwins, 1) * hdeskhalf) disp = SmartDisplay(visible=1, size=(wdeskhalf, hdeskhalf), position=mypos).start() print("** AddDisplay is: " + os.environ['DISPLAY'] + " " + os.environ['MATE_DESKTOP_SESSION_ID'] + " " + os.environ['DESKTOP_SESSION'] + " " + os.environ['XDG_CURRENT_DESKTOP']) disps.append((disp, os.environ['DISPLAY'])) # #mycmd='bash -c "echo AAA >> /tmp/test.log"' # shell redir has to be called like this! # # unfortunately, we cannot just call `nemo` here like the usual: # - it will take over the first Xephyr window as desktop manager, and all subsequent `nemo`s will open there; # however, we can use SSH X11 forwarding, which seems to fix that: # however, we must have mate-session (or gnome-session) ran before that; # else the wmctrl "cannot get client list properties"; mate-panel is not enough, but marco is (and it keeps small fonts - but adds titlebars) mycmd = 'ssh -XfC -c blowfish {}@localhost marco --replace --no-composite'.format( curuser) # -F ssh.config #mycmd='ssh -XfC -c blowfish {}@localhost tinywm'.format(curuser) # -F ssh.config # tinywm is so tiny, lists of windows are not managed print("mycmd: {}".format(mycmd)) #gscmdproc = EasyProcess(mycmd).start() #easyprocs.append(gscmdproc) ssh_cmd = pexpect.spawn(mycmd) ssh_cmd.expect('password: '******'t wait after this for EOF? time.sleep(0.25) ssh_cmd.expect(pexpect.EOF) sshconns.append(ssh_cmd) time.sleep(0.1) # mycmd = 'giggle /tmp' print("mycmd: {}".format(mycmd)) gigglecmdproc = EasyProcess(mycmd).start() easyprocs.append(gigglecmdproc) time.sleep(0.1) # mycmd = 'pcmanfm /tmp' print("mycmd: {}".format(mycmd)) pcmancmdproc = EasyProcess(mycmd).start() easyprocs.append(pcmancmdproc) time.sleep(0.1) # mycmd = [ 'gnome-terminal', '--working-directory=/tmp', '-e', r'bash -c "bash --rcfile <( echo source $HOME/.bashrc ; echo PS1=\\\"user@PC:\\\\[\\\\033[0\;33\;1m\\\\]\\\w\\\[\\\033[00m\\\]\\\\$ \\\" ) -i"' ] print("mycmd: {}".format(mycmd)) termcmdproc = EasyProcess(mycmd).start() easyprocs.append(termcmdproc)
def stop(self): ''' stop display :rtype: self ''' self.redirect_display(False) EasyProcess.stop(self) return self
def test_timeout_out(self): p = EasyProcess([ python, '-c', "import time;print( 'start');time.sleep(5);print( 'end')" ]).call(timeout=1) eq_(p.is_alive(), False) eq_(p.timeout_happened, True) ok_(p.return_code < 0) eq_(p.stdout, '')
def test_vncserver(): if worker() == 0: p = EasyProcess( [python, "-m", "pyvirtualdisplay.examples.vncserver"] ).start() sleep(1) assert p.is_alive() # p.stop() kill_process_tree(p)
def testrun(self, command, timeout=0.5): result = {'result': False} pro = EasyProcess(command.split()).call(timeout=timeout) if pro.return_code > 0: result['error'] = pro.stderr else: result['result'] = True pro.stop() return result
def backend_ref(backend): with Display(visible=0, size=(400, 500)): with EasyProcess('xlogo'): with EasyProcess('xmessage -center "%s"' % long_txt): time.sleep(2) for bbox in bbox_ls: print('bbox: %s' % (bbox, )) print('backend: %s' % backend) check_ref(backend, bbox)
def stop(self): ''' stop display :rtype: self ''' self.redirect_display(False) EasyProcess.stop(self) return self
def prog_shot(cmd, f, wait, timeout, screen_size, visible, bgcolor, backend): '''start process in headless X and create screenshot after 'wait' sec. Repeats screenshot until it is not empty if 'repeat_if_empty'=True. wait: wait at least N seconds after first window is displayed, it can be used to skip splash screen :param wait: int ''' # disp = SmartDisplay(visible=visible, size=screen_size, bgcolor=bgcolor) #'xvfb', 'xvnc' or 'xephyr', disp = SmartDisplay(visible=visible, backend=backend, size=screen_size, bgcolor=bgcolor) proc = EasyProcess(cmd) def cb_imgcheck(img): """accept img if height > minimum.""" rec = get_black_box(img) if not rec: return False left, upper, right, lower = rec accept = lower - upper > 30 # pixel log.debug('cropped img size=' + str((left, upper, right, lower)) + ' accepted=' + str(accept)) return accept # def func(): # if wait: # proc.sleep(wait) # try: # img = disp.waitgrab(timeout=timeout, cb_imgcheck=cb_imgcheck) # except DisplayTimeoutError as e: # raise DisplayTimeoutError(str(e) + ' ' + str(proc)) # return img with disp: with proc: try: if wait: proc.sleep(wait) img = disp.waitgrab(timeout=timeout, cb_imgcheck=cb_imgcheck) except DisplayTimeoutError as e: raise DisplayTimeoutError(str(e) + ' ' + str(proc)) # img = disp.wrap(proc.wrap(func))() if img: bbox = get_black_box(img) assert bbox # extend to the left side bbox = (0, bbox[1], bbox[2], bbox[3]) img = img.crop(bbox) img.save(f) return (proc.stdout, proc.stderr)
def test_double(): with SmartDisplay(visible=False, bgcolor="black") as disp: with EasyProcess(["xmessage", "hello1"]): img = disp.waitgrab() assert img is not None with SmartDisplay(visible=False, bgcolor="black") as disp: with EasyProcess(["xmessage", "hello2"]): img = disp.waitgrab() assert img is not None
def __init__(self): mutex.acquire() try: self.display = self.search_for_display() while self.display in USED_DISPLAY_NR_LIST: self.display+=1 USED_DISPLAY_NR_LIST.append(self.display) finally: mutex.release() EasyProcess.__init__(self, self._cmd)
def __init__(self): mutex.acquire() try: self.display = self.search_for_display() while self.display in USED_DISPLAY_NR_LIST: self.display += 1 USED_DISPLAY_NR_LIST.append(self.display) finally: mutex.release() EasyProcess.__init__(self, self._cmd)
def stop(self): ''' stop display :rtype: self ''' self.redirect_display(False) EasyProcess.stop(self) if self.use_xauth: self._clear_xauth() return self
def display(self, zipfilename='', block=True): fig = plt.figure() self.create(fig, zipfilename) if block: plt.show() else: p = EasyProcess([sys.executable, '-m', 'elme.start.plot', self.project.name, '--plot', self.name, '--zipfilename', zipfilename ]) p.start()
def generate(): #get the query if request.method == 'POST': query = request.form['query'] else: query = request.args.get('query') query = query.replace("\"","\\\"") command = "java -jar g.jar -qs \""+query+"\"" command_results = EasyProcess(command).call().stdout result = command_results.split("RDF Output:")[1] return str(result)
def __init__(self, use_xauth=False): mutex.acquire() try: self.display = self.search_for_display() while self.display in USED_DISPLAY_NR_LIST: self.display+=1 USED_DISPLAY_NR_LIST.append(self.display) finally: mutex.release() if use_xauth and not xauth.is_installed(): raise xauth.NotFoundError() self.use_xauth = use_xauth self._old_xauth = None self._xauth_filename = None EasyProcess.__init__(self, self._cmd)
def check_buttons(cmd, expect): with SmartDisplay(visible=VISIBLE) as disp: with EasyProcess(cmd): disp.waitgrab(timeout=TIMEOUT) buttons = discover_buttons() eq_(len(buttons), len(expect), msg='dialog does not have expected buttons %s!=%s' % (buttons,expect)) mouse = PyMouse() print 'buttons:',buttons for v, b in zip(expect, buttons): process = EasyProcess(cmd).start().sleep(1) mouse.click(*b.center) process.wait() eq_(process.stdout, str(v)) #dialog does not return expected value
def test_timeout(self): p = EasyProcess('sleep 1').start() p.wait(0.2) eq_(p.is_alive(), True) p.wait(0.2) eq_(p.is_alive(), True) p.wait(2) eq_(p.is_alive(), False) eq_(EasyProcess('sleep 0.3').call().return_code == 0, True) eq_(EasyProcess('sleep 0.3').call(timeout=0.1).return_code == 0, False) eq_(EasyProcess('sleep 0.3').call(timeout=1).return_code == 0, True) eq_(EasyProcess('sleep 0.3').call().timeout_happened, False) eq_(EasyProcess('sleep 0.3').call(timeout=0.1).timeout_happened, True) eq_(EasyProcess('sleep 0.3').call(timeout=1).timeout_happened, False)
def start(self): ''' start display :rtype: self ''' EasyProcess.start(self) # https://github.com/ponty/PyVirtualDisplay/issues/2 self.old_display_var = os.environ[ 'DISPLAY'] if 'DISPLAY' in os.environ else ':0' self.redirect_display(True) # wait until X server is active # TODO: better method time.sleep(0.1) return self
def service(request, service_mock): port = random.randint(30000, 40000) p = EasyProcess('python3.4 src/service.py {}' 'http://localhost:{}/tests/html1' .format(port, service_mock.port)) def turn_off(): print("DOWN") p.stop() print("STDOUT: " + p.stdout) print("STDERROR: " + p.stderr) print("CODE: " + str(p.return_code)) request.addfinalizer(turn_off) p.start() time.sleep(0.5) p.port = port return p
def take_screenshot(disp, file_name, timeout, out_file): # file_name = os.path.normpath(os.path.abspath(file_name)) if sys.platform.startswith('win'): file_name = '\\\\'.join(file_name.split('\\')) print('Starting {}'.format(file_name)) proc = EasyProcess(file_name).start() try: print('Wait for {} sec.'.format(timeout)) time.sleep(timeout) print('Taking screenshot') img = disp.waitgrab() print('Saving screenshot to {}'.format(out_file)) img.save(out_file) finally: proc.sendstop()
def start(self): """ start display :rtype: self """ if self.use_xauth: self._setup_xauth() EasyProcess.start(self) # https://github.com/ponty/PyVirtualDisplay/issues/2 # https://github.com/ponty/PyVirtualDisplay/issues/14 self.old_display_var = os.environ.get("DISPLAY", None) self.redirect_display(True) # wait until X server is active # TODO: better method time.sleep(0.1) return self
def sub_command(cmd_str, timeout=30, debug=False): """Run a command as child process using a timeout""" n = 3 while n: cmd = EasyProcess(cmd_str) cmd.call(timeout=timeout) if cmd.timeout_happened: info("Command failed due to timeout, retry!", debug) if n == 1: raise TimeoutError(u"Erreur lors de la commande: %s, temps de réponse "\ "trop long." % cmd_str) n -= 1 elif cmd.return_code or cmd.oserror: info("Command failed due unknown error, retry!", debug) if n == 1: raise CmdError(u"%s" % (cmd.stderr)) n -= 1 else: break return cmd.stdout
def start(self): ''' start display :rtype: self ''' if self.use_xauth: self._setup_xauth() EasyProcess.start(self) # https://github.com/ponty/PyVirtualDisplay/issues/2 # https://github.com/ponty/PyVirtualDisplay/issues/14 self.old_display_var = os.environ.get('DISPLAY', None) self.redirect_display(True) # wait until X server is active start_time = time.time() ok = False d = self.new_display_var while time.time() - start_time < X_START_TIMEOUT: try: exit_code = EasyProcess('xdpyinfo').call().return_code except EasyProcessError: log.warn('xdpyinfo was not found, X start can not be checked! Please install xdpyinfo!') time.sleep(X_START_WAIT) # old method ok = True break if exit_code != 0: pass else: log.info('Successfully started X with display "%s".', d) ok = True break time.sleep(X_START_TIME_STEP) if not ok: msg = 'Failed to start X on display "%s" (xdpyinfo check failed).' raise XStartTimeoutError(msg % d) return self
def test_deadlock(): d = Display(visible=VISIBLE, size=(600, 400)) d.start() p = EasyProcess([python, '-c', 'import Image;Image.new("RGB",(99, 99)).show()']) p.start() p.sleep(1) # hangs with pipes p.stop() d.stop()
def motors_monitor(self): cmd_dyn = 'rostopic echo /{}/safe/motor_states/default -n 1'.format(self.robot_name) while True: # Dynamixel states try: out = EasyProcess(cmd_dyn).call(timeout=1).stdout out = out[:out.rfind('\n')] states = yaml.load(out) self.dynamixel_motors_states = {m['id']: m for m in states['motor_states']} except: self.dynamixel_motors_states= {} # Pololu states for i in self.pololu_boards.keys(): cmd_pol = 'rostopic echo /{}/{}/motors_states -n 1'.format(self.robot_name, i) try: out = EasyProcess(cmd_pol).call(timeout=1).stdout out = out[:out.rfind('\n')] states = yaml.load(out) states = dict(zip(states['name'], states['position'])) self.pololu_boards[i] = states except: self.pololu_boards[i] = {} time.sleep(1)
def test_stop(self): p = EasyProcess('ls -la').start() time.sleep(0.2) eq_(p.stop().return_code, 0) eq_(p.stop().return_code, 0) eq_(p.stop().return_code, 0)
from easyprocess import EasyProcess query = '''BASE <http://example.org/> PREFIX rqg-ite: <http://w3id.org/sparql-generate/ite/> PREFIX rqg-fn: <http://w3id.org/sparql-generate/fn/> PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> GENERATE { [] rdfs:label ?body . } SOURCE <http://www.pdfconvertonline.com/htm-to-jpg-online.html> AS ?source ITERATOR rqg-ite:CSSPath(?source, "title") AS ?body WHERE { BIND(rqg-fn:HTMLTag(?body, "title") AS ?title ) }''' query = query.replace("\"","\\\"") command = "java -jar g.jar -qs \""+query+"\"" command_results = EasyProcess(command).call().stdout print command_results.split("RDF Output:")[1]
from config import Config from rdcc import Modem3G import datetime from datetime import datetime from datetime import timedelta import subprocess import ow import smtplib import xmlrpclib import socket from email.MIMEText import MIMEText from easyprocess import EasyProcess # third party modules REBOOT_CMD = EasyProcess("reboot -n -p") #----------------- Exceptions ------------------- class SensorError(Exception): def __init__(self, value): self.value = value def __str__(self): return self.value class TimeoutError(Exception): def __init__(self, value): self.value = value def __str__(self): return self.value
def __init__(self): self.display = self.search_for_display() EasyProcess.__init__(self, self._cmd)
def test_time_cli2(self): p = EasyProcess([python, '-c', "import logging;logging.basicConfig(level=logging.DEBUG);from easyprocess import EasyProcess;EasyProcess('sleep 5').call(timeout=0.5)"]) p.call() eq_(p.return_code, 0)
def test_time2(self): p = EasyProcess('sleep 5').call(timeout=1) eq_(p.is_alive(), False) eq_(p.timeout_happened, True) ok_(p.return_code < 0) eq_(p.stdout, '')
from easyprocess import EasyProcess from pyvirtualdisplay.smartdisplay import SmartDisplay disp = SmartDisplay(visible=0, bgcolor='black').start() xmessage = EasyProcess('xmessage hello').start() img = disp.waitgrab() xmessage.stop() disp.stop() img.show()
def test_slowshot_timeout(self): disp = SmartDisplay(visible=0) py = path(__file__).parent / ('slowgui.py') proc = EasyProcess('python ' + py) f = disp.wrap(proc.wrap(lambda: disp.waitgrab(timeout=1))) self.assertRaises(DisplayTimeoutError, f)
def test_empty(self): disp = SmartDisplay(visible=0) proc = EasyProcess(sys.executable) f = disp.wrap(proc.wrap(disp.waitgrab)) self.assertRaises(Exception, f)