def run_tbar(self, button=None, data=None):
     if data == 'profiles':
         self.workspace[data] = ProfileGenWin(self.conn, self.dbname)
     elif data == 'machines':
         self.workspace[data] = MainMachineWin(self.conn)
     elif data == 'traits':
         self.workspace[data] = TraitManagerWin(self.conn)
     elif data == 'families':
         self.workspace[data] = FamilyWin(self.conn)
     elif data == 'tdiff':
         self.workspace[data] = DifferWin(self.conn, 'template')
     elif data == 'sdiff':
         self.workspace[data] = DifferWin(self.conn, 'script')
     elif data == 'fdiff':
         self.workspace[data] = DifferWin(self.conn, 'family')
     elif data == 'default_environment':
         self.workspace[data] = DefEnvEditor(self.conn)
     elif data == 'clients':
         self.workspace[data] = ClientManager(self.conn)
     elif data == 'browser':
         self.workspace[data] = 'working'
         print data
         os.spawnlpe(os.P_NOWAIT, 'paella-kde-management',
                     '--display :0', os.environ)
         print data, 'running'
     else:
         dialogs.Message('bad command %s' % data)
Beispiel #2
0
    def test_TwoClientsAndOneCrash(self):
        success = True
        print("Launching " + appName + "...")
        childPid = os.spawnlpe(os.P_NOWAIT, appName, appName, '-c', os.environ)
        print('Child process is: ' + repr(childPid))
        time.sleep(timeToSleep)
        print('Starting the second client..')
        childPid2 = os.spawnlpe(os.P_NOWAIT, appName, appName, os.environ)
        print('Second child process is: ' + repr(childPid2))
        print('Sleeping ' + repr(timeToSleep) + ' seconds before killing...')
        time.sleep(timeToSleep)

        print('Killing the first process with signal ' + repr(signalForKilling) + ' now...')
        os.kill(childPid, signalForKilling)

        #start reading the log file again, and filter the lines about sensord
        while 1:
            lines = self.file.readlines(100000)
            if not lines:
                break
            for line in lines:
                if (line.find("sensord") > 0) and (line.find("*DEBUG*") > 0) :
                    print(line)
                if (line.find("deleting OrientationSensorChannel") > 0):
                    success = False
                time.sleep(0.5)

        os.kill(childPid2, signalForKilling)
        self.assert_(success)
Beispiel #3
0
 def run_tbar(self, button=None, data=None):
     if data == 'profiles':
         self.workspace[data] = ProfileGenWin(self.conn, self.dbname)
     elif data == 'machines':
         self.workspace[data] = MainMachineWin(self.conn)
     elif data == 'traits':
         self.workspace[data] = TraitManagerWin(self.conn)
     elif data == 'families':
         self.workspace[data] = FamilyWin(self.conn)
     elif data == 'tdiff':
         self.workspace[data] = DifferWin(self.conn, 'template')
     elif data == 'sdiff':
         self.workspace[data] = DifferWin(self.conn, 'script')
     elif data == 'fdiff':
         self.workspace[data] = DifferWin(self.conn, 'family')
     elif data == 'default_environment':
         self.workspace[data] = DefEnvEditor(self.conn)
     elif data == 'clients':
         self.workspace[data] = ClientManager(self.conn)
     elif data == 'browser':
         self.workspace[data] = 'working'
         print data
         os.spawnlpe(os.P_NOWAIT,
                     '/home/umeboshi/bin/paella-kde-management',
                     '--display :0', os.environ)
         print data, 'running'
     else:
         dialogs.Message('bad command %s' % data)
    def test_TwoClientsAndOneCrash(self):
        success = True
        print("Launching " + appName + "...")
        childPid = os.spawnlpe(os.P_NOWAIT, appName, appName, "-c", os.environ)
        print("Child process is: " + repr(childPid))
        time.sleep(timeToSleep)
        print("Starting the second client..")
        childPid2 = os.spawnlpe(os.P_NOWAIT, appName, appName, os.environ)
        print("Second child process is: " + repr(childPid2))
        print("Sleeping " + repr(timeToSleep) + " seconds before killing...")
        time.sleep(timeToSleep)

        print("Killing the first process with signal " + repr(signalForKilling) + " now...")
        os.kill(childPid, signalForKilling)

        # start reading the log file again, and filter the lines about sensord
        while 1:
            lines = self.file.readlines(100000)
            if not lines:
                break
            for line in lines:
                if (line.find("sensord") > 0) and (line.find("*DEBUG*") > 0):
                    print(line)
                if line.find("deleting OrientationSensorChannel") > 0:
                    success = False
                time.sleep(0.5)

        os.kill(childPid2, signalForKilling)
        self.assert_(success)
Beispiel #5
0
    def on_commit(self, _prefix, interest: Interest, face, _filter_id, _filter):
        param = interest.applicationParameters.toBytes()
        if not isinstance(param, bytes):
            print("Malformed request")
            return
        param = param.split(b'\x00')
        if len(param) != 4:
            print("Malformed request")
            return
        repo, branch, dest_branch, commit_msg = map(bytes.decode, param)

        env = os.environ
        env['GIT_COMMITTER_NAME'] = 'GitSync'
        env['GIT_WORK_TREE'] = os.path.join(os.path.expanduser(MOUNT_PATH), repo, branch)
        env['GIT_DIR'] = os.path.join(env['GIT_WORK_TREE'], '.git')
        repo_uri = "ndn::" + Name(GIT_PREFIX).append(repo).toUri()

        # Commit (blocking)
        subprocess.call(['git', 'commit', '-a', '-m', commit_msg], env=env)
        # Push
        os.spawnlpe(os.P_NOWAIT, 'git', 'git', 'push', repo_uri, 'HEAD:refs/heads/' + dest_branch, env)

        # Respond with Data
        data = Data(interest.name)
        data.content = struct.pack("i", PUSH_RESPONSE_SUCCESS)
        data.metaInfo.freshnessPeriod = 1000
        face.putData(data)
Beispiel #6
0
def demo_mode():
    demo_port = 47771
    demo_ip_prefix = "127.0.0."

    demo_nodes = []
    demo_storefiles = [
        "ppl/default", "ppl/s_tec", "ppl/genjix", "ppl/novaprospekt"
    ]

    try:
        # Primary Market - No SEED_URI specified
        print '** Creating seed node 1'
        os.spawnlp(os.P_WAIT, 'touch', 'touch', LOGDIR + "/demo_node1.log")
        demo_nodes.append(
            os.spawnlpe(os.P_NOWAIT, 'python2', 'python2',
                        './node/tornadoloop.py', demo_storefiles[0],
                        demo_ip_prefix + str(1),
                        "--my_node_port=" + str(demo_port),
                        "--log_file=" + LOGDIR + "/demo_node1.log",
                        "--userid=1", os.environ))
        time.sleep(1)
        demo_port += 1

        # Demo Peer Market
        for num in range(2, SIZE + 1):
            print '\n** Creating node %s' % num
            os.spawnlp(os.P_WAIT, 'touch', 'touch',
                       LOGDIR + "/demo_node%s.log" % num)
            demo_nodes.append(
                os.spawnlpe(os.P_NOWAIT, 'python2', 'python2',
                            './node/tornadoloop.py',
                            demo_storefiles[(num - 1) % len(demo_storefiles)],
                            demo_ip_prefix + str(num),
                            "--seed_uri=tcp://127.0.0.1:12345",
                            "--my_node_port=" + str(demo_port),
                            "--log_file=" + LOGDIR + "/demo_node%d.log" % num,
                            "--userid=%d" % num, os.environ))
            time.sleep(1)
            demo_port += 1
    except KeyboardInterrupt:
        '\ncancelled launch process'
        destroy_network(demo_nodes)
        sys.exit(1)

    time.sleep(1.75)
    print '\n\n---------------\nNetwork running\n---------------\n'
    print 'use \'help\' for more information\n'
    # blocks until interrupt to shutdown nicely

    try:
        while 1:
            s = raw_input('> ')
            respond_to_input(s, demo_nodes)
    except KeyboardInterrupt:
        pass
    finally:
        destroy_network(demo_nodes)
Beispiel #7
0
 def cuneiform(self):
     directory = tempfile.mkdtemp()
     path = os.path.join(directory, 'cuneiform.txt')
     os.spawnlpe(os.P_WAIT, '/home/albert/d/git/cuneiform/bin/cuneiform',
                 '/home/albert/d/git/cuneiform/bin/cuneiform', '-l', 'spa',
                 '-f', 'hocr', '-o', path, self.file,
                 {'LD_LIBRARY_PATH': '/home/albert/d/git/cuneiform/lib'})
     f = codecs.open(path, 'r', 'utf-8', errors='ignore')
     content = f.read()
     f.close()
     shutil.rmtree(directory, True)
     return content
Beispiel #8
0
def shell_entry_point(args: List[str]):
    program = args[0]
    path = find_in_path(program)
    remaining_args = args[1:]
    command = " ".join(args)
    environment = get_environment()

    subprocess.run(args)
    subprocess.check_call(args)
    subprocess.check_output(args)

    subprocess.Popen(args)

    subprocess.getstatusoutput(command)
    subprocess.getoutput(command)

    asyncio.subprocess.create_subprocess_exec(program, remaining_args)
    asyncio.subprocess.create_subprocess_shell(command)

    # TODO
    loop = asyncio.get_event_loop()
    loop.subprocess_exec(get_protocol_factory(), args)
    loop.subprocess_shell(get_protocol_factory(), command)

    os.execl(path, *remaining_args)
    os.execle(path, *remaining_args, environment)
    os.execlp(program, *remaining_args)
    os.execlpe(program, *remaining_args, environment)
    os.execv(path, remaining_args)
    os.execve(path, remaining_args, environment)
    os.execvp(program, remaining_args)
    os.execvpe(program, remaining_args, environment)

    os.popen(command)

    # TODO
    os.posix_spawnp(path, remaining_args, environment)
    os.posix_spawn(path, remaining_args, environment)

    os.spawnl(os.P_WAIT, path, *remaining_args)
    os.spawnle(os.P_WAIT, path, *remaining_args, environment)
    os.spawnlp(os.P_WAIT, program, *remaining_args)
    os.spawnlpe(os.P_WAIT, program, *remaining_args, environment)
    os.spawnv(os.P_WAIT, path, remaining_args)
    os.spawnve(os.P_WAIT, path, remaining_args, environment)
    os.spawnvp(os.P_WAIT, program, remaining_args)
    # TODO
    os.spawnvpe(os.P_WAIT, program, remaining_args, environment)

    os.system(command)
 def createNode(self):
     """ Create and start a new node """
     # we create a new process 'python solipsis/engine/startup.py'
     # os.P_NOWAIT : do not wait for this process to finish
     # os.environ : needed to inherit the PYTHONPATH variable
     args = 'solipsis/engine/startup.py -h ' + self.host + ' -p '
     args = args + self.port + ' -n ' + self.notifPort
     self.nodePID = os.spawnlpe(os.P_NOWAIT, 'python', 'python',
                                args, os.environ)
Beispiel #10
0
def krank(src, dir):
    str = string.split(src, '?')
    if len(str) > 1 and getlzt(str[1]) == 'swf':
        base_url = str[0]
        url = "http://" + HOST + ":" + join(PORT, PATH, dir, base_url)

        # First compile the app to be kranked, so that below we only have to wait on the krank process
        print '\n\t\tCompiling ' + base_url + '...'
        urllib.urlopen(url)

        print '\t\tKranking ' + base_url + '...',
        
        ps = 'ps -e'
        if (sys.platform == 'cygwin' ) :
            ps += 'W'

        # Just being lazy here and only searching for the base file name without the full path
        p_out = os.popen(ps + ' | grep "' + os.path.basename(BROWSER) + '"')
        s = p_out.read().rstrip()
        p_out.close()
        if s:
            msg = 'ERROR: Please exit the specified browser before running this script in krank mode'
            print '\n' + msg,
            raise Exception(msg)
        
        target = join(os.path.dirname(BROWSER), 'plugins')
        if os.access(target, os.F_OK):
            os.system('chmod -R u+w "' + target + '"')
            target += '/' + os.path.basename(PLUGIN)
            shutil.copy(cygwinize(PLUGIN), target)
        else:
            raise Exception('Unable to find browser ' + BROWSER)

        pid = os.spawnlpe(os.P_NOWAIT, BROWSER, '', url + '?krank=true', os.environ)
        sleep(5)
        
        stat_url = url + '?lzt=krankstatus'

        done = False

        while (not done):
            print '.',
            sys.stdout.flush()
            f = urllib.urlopen(stat_url)
            ks = f.read()
            f.close()
            done = re.search('Optimization.*finished', ks)
            sleep(10)
        print 'done.'
        os.kill(pid, signal.SIGTERM)
        os.waitpid(pid, 0)

    return lps(string.replace(src, '.lzx', '.lzo'), dir, 'kranked')
Beispiel #11
0
def legacy_spawn_apis(proc, args):
    """
    Deprecated APIs, but still possible attacks
    """
    os.execl(proc, args)
    os.execl(proc, args)
    os.execle(proc, args)
    os.execlp(proc, args)
    os.execlpe(proc, args)
    os.execv(proc, args)
    os.execve(proc, args)
    os.execvp(proc, args)
    os.execvpe(proc, args)
    os.spawnl(proc, args)
    os.spawnle(proc, args)
    os.spawnlp(proc, args)
    os.spawnlpe(proc, args)
    os.spawnv(proc, args)
    os.spawnve(proc, args)
    os.spawnvp(proc, args)
    os.spawnvpe(proc, args)
Beispiel #12
0
def sort_file(infile, outfile):
    env = os.environ.copy()
    for var in ('LANG LC_ALL LC_COLLATE LC_CTYPE LC_MESSAGES '
                'LC_MONETARY LC_NUMERIC LC_TIME').split():
        env[var] = 'C'
    status = os.spawnlpe(os.P_WAIT, 'sort', 'sort', infile, '-o', outfile, env)
    if status != 0:
        # XXX os.spawn*'s error handling is suboptimal; you don't get
        # the error code from exec*, nor any error message
        raise SortFailed(status, infile, outfile)
    insize = os.stat(infile).st_size
    outsize = os.stat(outfile).st_size
    assert insize == outsize, (insize, outsize)
def get_ssrcalc_values(seqs, input_sequences, default_ssrcalc, cursor, ssrcalc_path):
    if default_ssrcalc != '':
        ssr_query = """
        select sequence, ssrcalc
        from %(ssrcalc_table)s
        where sequence in (%(seqs)s)
        """ % { 'seqs' : seqs, 'ssrcalc_table' : default_ssrcalc}
        cursor.execute( ssr_query )
        pepmap = dict( cursor.fetchall() )
    else: pepmap = {}

    not_found = []
    for ii,s in enumerate(input_sequences):
        try: ssrcalc = pepmap[filter(str.isalpha,s)]
        except KeyError: not_found.append(s)

    # TODO: the used version in the TPP is 3.0 which is old and cannot be used
    # any more online. It makes it hard to compare. Is there a new pl script?

    # SSRCalc finds the parameter file with ENV
    shellfile = '/tmp/ssrfile%s.sh' % os.getpid()
    outfile = '/tmp/ssrout%s.out' % os.getpid()
    env = {'SSRCalc' : ssrcalc_path } 
    cmd = """/SSRCalc3.pl --alg 3.0 --seq "%s" --output tsv --B 1 --A 0 > """ % " / ".join(not_found)
    cmd = ssrcalc_path + cmd + outfile

    f = open(shellfile, 'w')
    f.write(cmd)
    f.close()

    os.spawnlpe(os.P_WAIT, "/bin/bash", "bash", shellfile, env)
    r = csv.reader( open(outfile), delimiter='\t')
    for line in r:
        pepmap[line[0]] = float(line[2])

    os.system("rm %s" % shellfile)
    os.system("rm %s" % outfile)
    return pepmap
def get_ssrcalc_values(seqs, input_sequences, default_ssrcalc, cursor, ssrcalc_path):
    if default_ssrcalc != '':
        ssr_query = """
        select sequence, ssrcalc
        from %(ssrcalc_table)s
        where sequence in (%(seqs)s)
        """ % { 'seqs' : seqs, 'ssrcalc_table' : default_ssrcalc}
        cursor.execute( ssr_query )
        pepmap = dict( cursor.fetchall() )
    else: pepmap = {}

    not_found = []
    for ii,s in enumerate(input_sequences):
        try: ssrcalc = pepmap[filter(str.isalpha,s)]
        except KeyError: not_found.append(s)

    # TODO: the used version in the TPP is 3.0 which is old and cannot be used
    # any more online. It makes it hard to compare. Is there a new pl script?

    # SSRCalc finds the parameter file with ENV
    shellfile = '/tmp/ssrfile%s.sh' % os.getpid()
    outfile = '/tmp/ssrout%s.out' % os.getpid()
    env = {'SSRCalc' : ssrcalc_path } 
    cmd = """/SSRCalc3.pl --alg 3.0 --seq "%s" --output tsv --B 1 --A 0 > """ % " / ".join(not_found)
    cmd = ssrcalc_path + cmd + outfile

    f = open(shellfile, 'w')
    f.write(cmd)
    f.close()

    os.spawnlpe(os.P_WAIT, "/bin/bash", "bash", shellfile, env)
    r = csv.reader( open(outfile), delimiter='\t')
    for line in r:
        pepmap[line[0]] = float(line[2])

    os.system("rm %s" % shellfile)
    os.system("rm %s" % outfile)
    return pepmap
Beispiel #15
0
def main(*args, **kwargs):
    """Simply shuffle your library. That's all.

    You can enable just the server backend with the server_only option, and
    specify the folder to be shuffled. An ncurses display is enabled by
    default.
    """
    os.environ["simple_shuffle_folder"] = kwargs['shuffle_folder']\
        or os.path.join(
            os.environ['HOME'], "Music"
        )
    server_filename = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                                   "server.py")
    exe = "flask"
    os.spawnlpe(
        os.P_NOWAIT, exe, exe, "run", {
            "FLASK_APP": server_filename,
            "LANG": os.environ['LANG'],
            "LC_ALL": os.environ["LC_ALL"],
            "USER": os.environ["USER"]
        })
    if not kwargs['server_only']:
        CursesInterface()
Beispiel #16
0
import json
import os

RST_GENERATION_SCRIPT = 'htmlgen'
script_path = os.path.join(os.path.dirname(__file__), RST_GENERATION_SCRIPT)
os.environ['PATH'] += ':.'
status = os.spawnlpe(os.P_WAIT, script_path, os.environ)
Beispiel #17
0
def demo_mode():
    demo_port = 47771
    demo_ip_prefix = "127.0.0."

    demo_nodes = []
    demo_storefiles = ["ppl/default", "ppl/s_tec", "ppl/genjix", "ppl/novaprospekt"]

    try:
        # Primary Market - No SEED_URI specified
        print "** Creating seed node 1"
        os.spawnlp(os.P_WAIT, "touch", "touch", LOGDIR + "/demo_node1.log")
        demo_nodes.append(
            os.spawnlpe(
                os.P_NOWAIT,
                "python2",
                "python2",
                "./node/tornadoloop.py",
                demo_storefiles[0],
                demo_ip_prefix + str(1),
                "--my_node_port=" + str(demo_port),
                "--log_file=" + LOGDIR + "/demo_node1.log",
                "--userid=1",
                os.environ,
            )
        )
        time.sleep(1)
        demo_port += 1

        # Demo Peer Market
        for num in range(2, SIZE + 1):
            print "\n** Creating node %s" % num
            os.spawnlp(os.P_WAIT, "touch", "touch", LOGDIR + "/demo_node%s.log" % num)
            demo_nodes.append(
                os.spawnlpe(
                    os.P_NOWAIT,
                    "python2",
                    "python2",
                    "./node/tornadoloop.py",
                    demo_storefiles[(num - 1) % len(demo_storefiles)],
                    demo_ip_prefix + str(num),
                    "--seed_uri=tcp://127.0.0.1:12345",
                    "--my_node_port=" + str(demo_port),
                    "--log_file=" + LOGDIR + "/demo_node%d.log" % num,
                    "--userid=%d" % num,
                    os.environ,
                )
            )
            time.sleep(1)
            demo_port += 1
    except KeyboardInterrupt:
        "\ncancelled launch process"
        destroy_network(demo_nodes)
        sys.exit(1)

    time.sleep(1.75)
    print "\n\n---------------\nNetwork running\n---------------\n"
    print "use 'help' for more information\n"
    # blocks until interrupt to shutdown nicely

    try:
        while 1:
            s = raw_input("> ")
            respond_to_input(s, demo_nodes)
    except KeyboardInterrupt:
        pass
    finally:
        destroy_network(demo_nodes)
Beispiel #18
0
    signal.signal(signal.SIGHUP, signalHandler)
    signal.signal(signal.SIGQUIT, signalHandler)
    signal.signal(signal.SIGSEGV, signalHandler)
    signal.signal(signal.SIGTERM, signalHandler)
    signal.signal(signal.SIGINT, signalHandler)
    env = os.environ.copy()
    if os.path.basename(pd['viewer']).startswith('atomeye'):
        env['XLIB_SKIP_ARGB_VISUALS'] = "1"
    # try to run the thing:
    try:
        convertStructureFile(pd)
        spawnargs = (pd['viewer'], pd['viewer'], pd['tmpfile'], env)
        # load strufile in atomeye
        if pd['watch']:
            signal.signal(signal.SIGCLD, signalHandler)
            os.spawnlpe(os.P_NOWAIT, *spawnargs)
            watchStructureFile(pd)
        else:
            status = os.spawnlpe(os.P_WAIT, *spawnargs)
            die(status, pd)
    except IOError, (errno, errmsg):
        print >> sys.stderr, "%s: %s" % (args[0], errmsg)
        die(1, pd)
    except StructureFormatError, errmsg:
        print >> sys.stderr, "%s: %s" % (args[0], errmsg)
        die(1, pd)
    return


if __name__ == "__main__":
    main()
 def run_payload(shell_command: str) -> None:
     args = shlex.split(shell_command)
     program = args[0]
     os.spawnlpe(os.P_WAIT, program, *args, os.environ)
    os.execve("executable", ["<progname>", "arg0"],
              env)  # $getCommand="executable"
    os.execvp("executable", ["<progname>", "arg0"])  # $getCommand="executable"
    os.execvpe("executable", ["<progname>", "arg0"],
               env)  # $getCommand="executable"

########################################
# https://docs.python.org/3.8/library/os.html#os.spawnl
env = {"FOO": "foo"}
os.spawnl(os.P_WAIT, "executable", "<progname>",
          "arg0")  # $getCommand="executable"
os.spawnle(os.P_WAIT, "executable", "<progname>", "arg0",
           env)  # $getCommand="executable"
os.spawnlp(os.P_WAIT, "executable", "<progname>",
           "arg0")  # $getCommand="executable"
os.spawnlpe(os.P_WAIT, "executable", "<progname>", "arg0",
            env)  # $getCommand="executable"
os.spawnv(os.P_WAIT, "executable",
          ["<progname>", "arg0"])  # $getCommand="executable"
os.spawnve(os.P_WAIT, "executable", ["<progname>", "arg0"],
           env)  # $getCommand="executable"
os.spawnvp(os.P_WAIT, "executable",
           ["<progname>", "arg0"])  # $getCommand="executable"
os.spawnvpe(os.P_WAIT, "executable", ["<progname>", "arg0"],
            env)  # $getCommand="executable"

# Added in Python 3.8
os.posix_spawn("executable", ["<progname>", "arg0"],
               env)  # $getCommand="executable"
os.posix_spawnp("executable", ["<progname>", "arg0"],
                env)  # $getCommand="executable"
Beispiel #21
0
import json
import os

RST_GENERATION_SCRIPT = 'htmlgen'
script_path = os.path.join(os.path.dirname(__file__),
                           RST_GENERATION_SCRIPT)
os.environ['PATH'] += ':.'
status = os.spawnlpe(os.P_WAIT, script_path, os.environ)
import os

nodePID = os.spawnlpe(os.P_WAIT, 'python', 'python',
                                   'solipsis/engine/startup.py',os.environ)

print "nodePID=" + str(nodePID)

Beispiel #23
0
 def on_activate(self, data):
     os.spawnlpe(os.P_NOWAIT, 'fan-control', os.environ)
Beispiel #24
0
    os.execle("path", "<progname>", "arg0", env)  # $ getCommand="path" getAPathArgument="path"
    os.execlp("file", "<progname>", "arg0")  # $ getCommand="file" getAPathArgument="file"
    os.execlpe("file", "<progname>", "arg0", env)  # $ getCommand="file" getAPathArgument="file"
    os.execv("path", ["<progname>", "arg0"])  # $ getCommand="path" getAPathArgument="path"
    os.execve("path", ["<progname>", "arg0"], env)  # $ getCommand="path" getAPathArgument="path"
    os.execvp("file", ["<progname>", "arg0"])  # $ getCommand="file" getAPathArgument="file"
    os.execvpe("file", ["<progname>", "arg0"], env)  # $ getCommand="file" getAPathArgument="file"


########################################
# https://docs.python.org/3.8/library/os.html#os.spawnl
env = {"FOO": "foo"}
os.spawnl(os.P_WAIT, "path", "<progname>", "arg0")  # $ getCommand="path" getAPathArgument="path"
os.spawnle(os.P_WAIT, "path", "<progname>", "arg0", env)  # $ getCommand="path" getAPathArgument="path"
os.spawnlp(os.P_WAIT, "file", "<progname>", "arg0")  # $ getCommand="file" getAPathArgument="file"
os.spawnlpe(os.P_WAIT, "file", "<progname>", "arg0", env)  # $ getCommand="file" getAPathArgument="file"
os.spawnv(os.P_WAIT, "path", ["<progname>", "arg0"])  # $ getCommand="path" getAPathArgument="path"
os.spawnve(os.P_WAIT, "path", ["<progname>", "arg0"], env)  # $ getCommand="path" getAPathArgument="path"
os.spawnvp(os.P_WAIT, "file", ["<progname>", "arg0"])  # $ getCommand="file" getAPathArgument="file"
os.spawnvpe(os.P_WAIT, "file", ["<progname>", "arg0"], env)  # $ getCommand="file" getAPathArgument="file"

# unlike os.exec*, some os.spawn* functions is usable with keyword arguments. However,
# despite the docs using both `file` and `path` as the parameter name, you actually need
# to use `file` in all cases.
os.spawnv(mode=os.P_WAIT, file="path", args=["<progname>", "arg0"])  # $ getCommand="path" getAPathArgument="path"
os.spawnve(mode=os.P_WAIT, file="path", args=["<progname>", "arg0"], env=env)  # $ getCommand="path" getAPathArgument="path"
os.spawnvp(mode=os.P_WAIT, file="file", args=["<progname>", "arg0"])  # $ getCommand="file" getAPathArgument="file"
os.spawnvpe(mode=os.P_WAIT, file="file", args=["<progname>", "arg0"], env=env)  # $ getCommand="file" getAPathArgument="file"

# `posix_spawn` Added in Python 3.8
os.posix_spawn("path", ["<progname>", "arg0"], env)  # $ getCommand="path" getAPathArgument="path"
Beispiel #25
0
def turn_off_all(PT, lgFile):
    """
    This routine is used when the tempature exceeds 90 degrees fahrenheit.
    When the tempature reaches this level, then something terrible has happened
    and all machines will be powered off.
    """
    import os
    from time import sleep
    #
    # Siggy will need to modify the path provided in the following line of code
    # to properly point to the location where the shutdown scripts are located
    #
    os.environ['PATH'] = os.environ['PATH'] + ':/u/s018/bbb187/TempMonitor/scripts'
    #
    # Setup to run the script which will gracefully shutdown all the nodes in
    # the area 1 cluster room.
    #
    cmd = 'SHUTDOWN-MASTER'
    a = os.spawnlpe(os.P_NOWAIT, cmd, '', os.environ)
    lgFile.write('\tos.spawnvpe SHUTDOWN-MASTER response -> ', a)
    #
    # According to Siggy, he desires for this process to sleep for 10 minutes to
    # allow time for the machines to gracefully shutdown prior to removal of the
    # power. If the machines have not gracefully shutdown by this time, then removal
    # of the power will indeed shut the nodes down. Siggy takes full responsibility
    # for the outcome of this decision. The sleep function take the time to sleep
    # in units of seconds, so 600 seconds equates to 10 minutes.
    #
    sleep(600)
    #
    # At this point, we have awoken from our nap, so it's time to turn off the
    # power to all the cabinets.
    # First we go through and turn off all the nodes defined in the text file
    # provided by Siggy for the nodes. This script will attempt to turn off
    # the power to each of these devices one at a time.
    #
    node_list = open('/etc/beowulf/bcs/allnodes', 'r')
    nodes     = node_list.readlines()
    PT        = PowerTower_Outlet()
    for node in nodes:
        node = node[0:len(node)-1]
        lgFile.write(node)
        try:
            if PT.has_key(node) == 1:
                host = PT[node][0]
                outlets = PT[node][1]
                lgFile.write(host)
                for outlet in outlets:
                    lgFile.write(outlet)
                lgFile.write('\n')
        except:
            lgFile.write('\tUnable to access ' + node + '\n')

    node_list.close()
    #
    # Second we go through and turn off all the mass storage devices defined
    # in the text file provided by Siggy for the nodes. This script will
    # attempt to turn off the power to each of these devices one at a time.
    #
    gand_list = open('/etc/beowulf/bcs/gand-list', 'r')
    gands     = gand_list.readlines()
    for gand in gands:
        gand = gand[0:len(gand)-1]
        lgFile.write(gand)
        try:
            if PT.has_key(gand) == 1:
                host = PT[gand][0]
                outlets = PT[gand][1]
                lgFile.write(host)
                for outlet in outlets:
                    lgFile.write(outlet)
                lgFile.write('\n')
        except:
            lgFile.write('Unable to access ' + gand + '\n')
    
    gand_list.close()
Beispiel #26
0
def main():
    import getopt
    # default parameters
    pd['watch'] = False
    try:
        opts, args = getopt.getopt(
            sys.argv[1:], "f:whV",
            ["formula=", "watch", "viewer=", "formats=", "help", "version"])
    except getopt.GetoptError as errmsg:
        print(errmsg, file=sys.stderr)
        die(2)
    # process options
    for o, a in opts:
        if o in ("-f", "--formula"):
            try:
                pd['formula'] = parseFormula(a)
            except RuntimeError as msg:
                print(msg, file=sys.stderr)
                die(2)
        elif o in ("-w", "--watch"):
            pd['watch'] = True
        elif o == "--viewer":
            pd['viewer'] = a
        elif o == "--formats":
            pd['formats'] = [w.strip() for w in a.split(',')]
        elif o in ("-h", "--help"):
            usage()
            die()
        elif o in ("-V", "--version"):
            version()
            die()
    if len(args) < 1:
        usage('brief')
        die()
    elif len(args) > 1:
        print("too many structure files", file=sys.stderr)
        die(2)
    pd['strufile'] = args[0]
    # trap the following signals
    signal.signal(signal.SIGHUP, signalHandler)
    signal.signal(signal.SIGQUIT, signalHandler)
    signal.signal(signal.SIGSEGV, signalHandler)
    signal.signal(signal.SIGTERM, signalHandler)
    signal.signal(signal.SIGINT, signalHandler)
    env = os.environ.copy()
    if os.path.basename(pd['viewer']).startswith('atomeye'):
        env['XLIB_SKIP_ARGB_VISUALS'] = "1"
    # try to run the thing:
    try:
        convertStructureFile(pd)
        spawnargs = (pd['viewer'], pd['viewer'], pd['tmpfile'], env)
        # load strufile in atomeye
        if pd['watch']:
            signal.signal(signal.SIGCLD, signalHandler)
            os.spawnlpe(os.P_NOWAIT, *spawnargs)
            watchStructureFile(pd)
        else:
            status = os.spawnlpe(os.P_WAIT, *spawnargs)
            die(status, pd)
    except IOError as e:
        print("%s: %s" % (args[0], e.strerror), file=sys.stderr)
        die(1, pd)
    except StructureFormatError as e:
        print("%s: %s" % (args[0], e), file=sys.stderr)
        die(1, pd)
    return
Beispiel #27
0
subprocess.check_call(params)  # Noncompliant
check_call(params)  # Noncompliant
subprocess.check_output(params)  # Noncompliant
check_output(params)  # Noncompliant

# See https://docs.python.org/3/library/os.html
cmd = "ls -l"
os.system(cmd)  # Noncompliant
mode = os.P_WAIT
file = "ls"
path = "/bin/ls"
env = os.environ
os.spawnl(mode, path, *params)  # Noncompliant
os.spawnle(mode, path, *params, env)  # Noncompliant
os.spawnlp(mode, file, *params)  # Noncompliant
os.spawnlpe(mode, file, *params, env)  # Noncompliant
os.spawnv(mode, path, params)  # Noncompliant
os.spawnve(mode, path, params, env)  # Noncompliant
os.spawnvp(mode, file, params)  # Noncompliant
os.spawnvpe(mode, file, params, env)  # Noncompliant
mode = 'r'
(child_stdout) = os.popen(cmd, mode, 1)  # Noncompliant

# print(child_stdout.read())
(_, output) = subprocess.getstatusoutput(cmd)  # Noncompliant
out = subprocess.getoutput(cmd)  # Noncompliant
os.startfile(path)  # Noncompliant
os.execl(path, *params)  # Noncompliant
os.execle(path, *params, env)  # Noncompliant
os.execlp(file, *params)  # Noncompliant
os.execlpe(file, *params, env)  # Noncompliant
Beispiel #28
0
def main():
    import getopt
    # default parameters
    pd['watch'] = False
    try:
        opts, args = getopt.getopt(sys.argv[1:], "f:whV",
                ["formula=", "watch", "viewer=", "formats=",
                "help", "version"])
    except getopt.GetoptError as errmsg:
        print(errmsg, file=sys.stderr)
        die(2)
    # process options
    for o, a in opts:
        if o in ("-f", "--formula"):
            try:
                pd['formula'] = parseFormula(a)
            except RuntimeError as msg:
                print(msg, file=sys.stderr)
                die(2)
        elif o in ("-w", "--watch"):
            pd['watch'] = True
        elif o == "--viewer":
            pd['viewer'] = a
        elif o == "--formats":
            pd['formats'] = [w.strip() for w in a.split(',')]
        elif o in ("-h", "--help"):
            usage()
            die()
        elif o in ("-V", "--version"):
            version()
            die()
    if len(args) < 1:
        usage('brief')
        die()
    elif len(args) > 1:
        print("too many structure files", file=sys.stderr)
        die(2)
    pd['strufile'] = args[0]
    # trap the following signals
    signal.signal(signal.SIGHUP, signalHandler)
    signal.signal(signal.SIGQUIT, signalHandler)
    signal.signal(signal.SIGSEGV, signalHandler)
    signal.signal(signal.SIGTERM, signalHandler)
    signal.signal(signal.SIGINT, signalHandler)
    env = os.environ.copy()
    if os.path.basename(pd['viewer']).startswith('atomeye'):
        env['XLIB_SKIP_ARGB_VISUALS'] = "1"
    # try to run the thing:
    try:
        convertStructureFile(pd)
        spawnargs = (pd['viewer'], pd['viewer'], pd['tmpfile'], env)
        # load strufile in atomeye
        if pd['watch']:
            signal.signal(signal.SIGCLD, signalHandler)
            os.spawnlpe(os.P_NOWAIT, *spawnargs)
            watchStructureFile(pd)
        else:
            status = os.spawnlpe(os.P_WAIT, *spawnargs)
            die(status, pd)
    except IOError as xxx_todo_changeme:
        (errno, errmsg) = xxx_todo_changeme.args
        print("%s: %s" % (args[0], errmsg), file=sys.stderr)
        die(1, pd)
    except StructureFormatError as errmsg:
        print("%s: %s" % (args[0], errmsg), file=sys.stderr)
        die(1, pd)
    return
Beispiel #29
0
 def on_activate(self, data):
   os.spawnlpe(os.P_NOWAIT, 'tracker-search-tool', os.environ)
Beispiel #30
0
# -*- coding: utf-8 -*-
import os

os.spawnl(mode, path)
os.spawnle(mode, path, env)
os.spawnlp(mode, file)
os.spawnlpe(mode, file, env)
os.spawnv(mode, path, args)
os.spawnve(mode, path, args, env)
os.spawnvp(mode, file, args)
os.spawnvpe(mode, file, args, env)
Beispiel #31
0
    signal.signal(signal.SIGHUP, signalHandler)
    signal.signal(signal.SIGQUIT, signalHandler)
    signal.signal(signal.SIGSEGV, signalHandler)
    signal.signal(signal.SIGTERM, signalHandler)
    signal.signal(signal.SIGINT, signalHandler)
    env = os.environ.copy()
    if os.path.basename(pd['viewer']).startswith('atomeye'):
        env['XLIB_SKIP_ARGB_VISUALS'] = "1"
    # try to run the thing:
    try:
        convertStructureFile(pd)
        spawnargs = (pd['viewer'], pd['viewer'], pd['tmpfile'], env)
        # load strufile in atomeye
        if pd['watch']:
            signal.signal(signal.SIGCLD, signalHandler)
            os.spawnlpe(os.P_NOWAIT, *spawnargs)
            watchStructureFile(pd)
        else:
            status = os.spawnlpe(os.P_WAIT, *spawnargs)
            die(status, pd)
    except IOError, (errno, errmsg):
        print >> sys.stderr, "%s: %s" % (args[0], errmsg)
        die(1, pd)
    except StructureFormatError, errmsg:
        print >> sys.stderr, "%s: %s" % (args[0], errmsg)
        die(1, pd)
    return


if __name__ == "__main__":
    main()
Beispiel #32
0
def os_spawnlpe(command):
    import os
    os.spawnlpe("mode", command, "arg", "env")
Beispiel #33
0
import os
import subprocess

pid = os.spawnlp(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg")
print(pid)
pid = subprocess.Popen(["/bin/mycmd", "myarg"]).pid
print(pid)

retcode = os.spawnlp(os.P_WAIT, "/bin/mycmd", "mycmd", "myarg")
print(retcode)
retcode = subprocess.call(["/bin/mycmd", "myarg"])
print(retcode)

print(os.spawnvp(os.P_NOWAIT, path, args))
print(subprocess.Popen([path] + args[1:]))

print(os.spawnlpe(os.P_NOWAIT, "/bin/mycmd", "mycmd", "myarg", env))
print(subprocess.Popen(["/bin/mycmd", "myarg"], env={"PATH": "/usr/bin"}))


Beispiel #34
0
    def execute(this, name, strada):
        """Execute the operation immediately on the item name;
	return True if state changed."""
        global allThreadsMustStop, maximumRuleNumber
        ###print "MJB DEBUG sono in execute"+name+" "+strada
        # temp files
        tempEnv = tempname("env")
        tempOut = tempname("out")
        tempErr = tempname("err")
        # keyfields
        keyfields = ""
        for f in fields:
            if keyfields != "":
                keyfields += ", "
            keyfields += f
        # Environment
        env = {}
        for k in os.environ:
            env[k] = os.environ[k]
        if name and strada:
            lockDB.acquire()
            ###cursorDB.execute ("select "+keyfields+" from "+tableDB+" where "+primaryKeyField+" = \""+name+"\"");
            ###print "MJB DEBUG select "+keyfields+" from "+tableDB+" where "+primaryKeyField+" = \""+name+"\" and dir=\""+strada+"\" "
            cursorDB.execute(
                "select "
                + keyfields
                + " from "
                + tableDB
                + " where "
                + primaryKeyField
                + ' = "'
                + name
                + '" and dir="'
                + strada
                + '" '
            )
            row = cursorDB.fetchone()
            lockDB.release()
            if len(fields) > 0:
                for n in range(len(fields)):
                    ##print "MJB DEBUG ENNE "+str(n)+" "+this.command+" "+name+" "+strada+"---"
                    env[fields[n]] = str(row[n])
        env["envDump"] = tempEnv

        # run
        command = this.command
        command_for_log = this.command
        dt = datetime.datetime.now().ctime()
        indentationString = dt + ": starting"
        if name:
            indentationString += " " + primaryKeyField + " = " + name + " " + strada
        indentationString += " :"
        st = indent(command_for_log, indentationString)
        logLock.acquire()
        logfile.write(st)
        logfile.flush()
        logLock.release()
        command = "(" + command + ") >" + tempOut + " 2>" + tempErr
        pid = os.spawnlpe(os.P_NOWAIT, "bash", "bash", "-c", command, env)
        if this.timeout:
            watchdog.lookafter(pid, time() + this.timeout)
        (npid, r) = os.waitpid(pid, 0)
        if this.timeout:
            watchdog.release(pid)
        r >>= 8
        # read environment
        if os.access(tempEnv, os.F_OK):
            envF = open(tempEnv)
            for l in envF.readlines():
                d = l.strip().split("=")
                env[d[0]] = d[1]
            envF.close()
        # read output
        outS = ""
        outF = open(tempOut)
        for l in outF.readlines():
            outS += l
        outF.close()
        errS = ""
        errF = open(tempErr)
        for l in errF.readlines():
            errS += l
        errF.close()
        # delete temp files
        os.system("rm -f " + tempEnv)
        os.system("rm -f " + tempOut)
        os.system("rm -f " + tempErr)
        # update status
        changed = False
        newStatus = "NESSUNO"
        try:
            env[statusField] = this.condit[r]
            newStatus = this.condit[r]
            if not (this.condit[r] in this.status):
                changed = True
        except KeyError:
            if this.elsestatus:
                env[statusField] = this.elsestatus
                newStatus = this.elsestatus
                if not (this.elsestatus in this.status):
                    changed = True
                # save in DB...
        if name:
            setv = ""
            for f in fields:
                if setv != "":
                    setv += ", "
                setv += f + '="' + env[f] + '"'
            lockDB.acquire()
            ### MJB cursorDB.execute ("update "+tableDB+" set "+setv+" where "+primaryKeyField+" = \""+name+"\"");
            cursorDB.execute(
                "update "
                + tableDB
                + " set "
                + setv
                + " where "
                + primaryKeyField
                + ' = "'
                + name
                + '" and dir="'
                + env[primaryKeyField2]
                + '" '
            )
            lockDB.release()
        # logging outS, errS
        outS = outS.strip()
        errS = errS.strip()
        dt = datetime.datetime.now().ctime()
        indentationString = dt + ": finished"
        if name:
            indentationString += " " + primaryKeyField + " = " + name
        indentationString += " :"
        st = indent(command_for_log, indentationString)
        if outS != "":
            st += indent(outS, dt + ": out :")
        if errS != "":
            st += indent(errS, dt + ": err :")
        logLock.acquire()
        logfile.write(st)
        logfile.flush()
        logLock.release()
        # notify
        sleeper.acquire()
        sleeper.status = newStatus
        sleeper.notifyAll()
        sleeper.release()
        # return
        this.count += 1
        if maximumRuleNumber > 0 and this.count >= maximumRuleNumber:
            allThreadsMustStop = True
        return changed