Beispiel #1
0
def hoptoad_deploy(deployed=False):
    """Notify Hoptoad of the time and commit SHA of an app deploy.

    Requires the hoppy Python package and the env keys:

        hoptoad_api_key - as it sounds.
        deployment_type - app environment
        release - the commit SHA or git tag of the deployed version
        scm - path to the remote git repository
    """
    require('hoptoad_api_key')
    require('deployment_type')
    require('release')
    require('scm')
    if deployed and env.hoptoad_api_key:
        commit = local('git rev-parse --short %(release)s' % env,
                capture=True)
        import hoppy.deploy
        hoppy.api_key = env.hoptoad_api_key
        try:
            hoppy.deploy.Deploy().deploy(
                env=env.deployment_type,
                scm_revision=commit,
                scm_repository=env.scm,
                local_username=os.getlogin())
        except Exception, e:
            print ("Couldn't notify Hoptoad of the deploy, but continuing "
                    "anyway: %s" % e)
        else:
            print ('Hoptoad notified of deploy of %s@%s to %s environment by %s'
                    % (env.scm, commit, env.deployment_type, os.getlogin()))
Beispiel #2
0
def kill_running_program(binaryPath):
    if sys.platform in ("darwin", "Darwin"):
        checkPath = os.path.split(binaryPath)[1]
        if not checkPath:
            return
        cmd = "ps -ef | grep %s | grep %s | grep -v grep | awk '{print $2}'" % (os.getlogin(), checkPath)
        res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()
        pids = res[0].split("\n")
        for pid in pids:
            if pid.strip() != "":
                os.kill(int(pid.strip()), signal.SIGTERM)
    else:
        if binaryPath.find("qfsstatus") >= 0:
            cmd = "ps -ef | grep %s | grep /qfsbase/ | grep %s | grep -v grep | awk '{print $2}'" % (
                os.getlogin(),
                binaryPath,
            )
            res = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE).communicate()
            pids = res[0].split("\n")
            for pid in pids:
                if pid.strip() != "":
                    os.kill(int(pid.strip()), signal.SIGTERM)
            return

        pids = subprocess.Popen(["pidof", binaryPath], stdout=subprocess.PIPE).communicate()
        for pid in pids[0].strip().split():
            os.kill(int(pid), signal.SIGTERM)
Beispiel #3
0
 def drop_perms( self ):
     """ Drop the permissions down from root """
     import pwd
     uid = pwd.getpwnam( os.getlogin() )[2]
     gid = pwd.getpwnam( os.getlogin() )[3]
     os.setgid( gid )
     os.setuid( uid )
    def get_test_scripts_from_svn(self):        
        os.chdir("/home/"+os.getlogin()+"/自动测试/9-全面测试(新)") 
        file_list = os.listdir(os.getcwd())
        newest_file=str(max([entry for entry in file_list if "自动化测试项目-全面测试--日期" in str(entry)]))

        os.chdir(self.get_working_dir())     
        commands.getstatusoutput("rm -fr * ")
        command = "cp "+"/home/"+os.getlogin()+"/自动测试/9-全面测试(新)"+os.sep+newest_file+"  "+self.get_working_dir()+os.sep
        commands.getstatusoutput(command)
        command = "unzip"+" "+newest_file 
        commands.getstatusoutput(command)
        inner_dir = "/home/"+os.getlogin()+"/automation_testing/git-opdog/opdog/TestCases/CDOS2.0"
        #smoke
        command ="cp -fr "+inner_dir+'/冒烟测试'+'   '+self.get_working_dir("smoke_test")
        commands.getstatusoutput(command)
        #function
        command ="cp -fr "+inner_dir+'/功能测试'+'   '+self.get_working_dir("function_test")
        commands.getstatusoutput(command)
        #stress and stability
        command ="cp -fr "+inner_dir+'/稳定性和可靠性测试'+'   '+self.get_working_dir("stability_test")
        commands.getstatusoutput(command)
        #basic
        command ="cp -fr "+inner_dir+'/基础测试'+'   '+self.get_working_dir("base_test")
        commands.getstatusoutput(command)
        #component
        command ="cp -fr "+inner_dir+'/部件测试'+'   '+self.get_working_dir("component_test")
        commands.getstatusoutput(command)
Beispiel #5
0
    def __auth_header(self, error, uri, method, args_get, args_post):
        if self.auth_tries > self.max_auth_tries:
            raise ClientAuthException('To many authentication failures')
        self.auth_tries += 1

        if self.as_module and not self.username and not self.password:
            raise ClientAuthException('When using as module, please initiate class with username and password')

        while not self.username:
            self.username = raw_input('Username [%s]: ' % os.getlogin())
            if not self.username:
                self.username = os.getlogin()

        while not self.password:
            self.password = getpass.getpass('Password: '******'WWW-Authenticate', None)

        if realm_header:
            realm_found = self.realm_matcher.findall(realm_header)
            if len(realm_found) > 1:
                raise ClientAuthException('Unable to determine realm name')
            elif realm_found and len(realm_found) < 1:
                realm_found = None
            else:
                realm_found = realm_found[0]
        else:
            realm_found = False

        auth_handler = urllib2.HTTPBasicAuthHandler()
        auth_handler.add_password(realm_found, uri, self.username, self.password)
        self.opener.add_handler(auth_handler)
        return self.__request(uri, method=method, args_get=args_get, args_post=args_post)
 def get_configurations(self):
     main_folder = str(os.environ['HOME']) + "/pt_video_downloader"
     fl = shelve.open("%s/app_data/configs.dat" % main_folder)
     try:
         ret = fl['configs']
     except:
         os.makedirs("/home/%s/Videos/PtVideoDownloader" % os.getlogin(), exist_ok=True)
         fl['configs'] = {
             'download':{
                 'down_path': {
                     'title': 'Download Target Path',
                     'value': str.format('/home/{0}/Videos/PtVideoDownloader/', os.getlogin()),
                     'type': 'file'
                     },
                 'down_after_remove': {
                     'title': 'Remove Downloaded Videos',
                     'value': True,
                     'type': 'bool'
                     }
             },
             'search':{
                 'search_max_result_count': {
                     'title': 'Maximum Search Results',
                     'value': 10,
                     'type': 'int'
                 }
             }
         }
         ret = fl['configs']
     finally:
         fl.close()
     return ret
Beispiel #7
0
def kill_running_program(binaryPath):
    if sys.platform in ('darwin', 'Darwin'):
        checkPath = os.path.split(binaryPath)[1]
        if not checkPath:
            return
        cmd = ('ps -ef | grep %s | grep %s | grep -v grep | awk \'{print $2}\''
               % (os.getlogin(), checkPath))
        res = subprocess.Popen(cmd, shell=True,
                               stdout=subprocess.PIPE).communicate()
        pids = res[0].split('\n')
        for pid in pids:
            if pid.strip() != '':
                os.kill(int(pid.strip()), signal.SIGTERM)
    else:
        if binaryPath.find('qfsstatus') >= 0:
            cmd = ('ps -ef | grep %s | grep /qfsbase/ | grep %s | grep -v grep | awk \'{print $2}\''
                   % (os.getlogin(), binaryPath))
            res = subprocess.Popen(cmd, shell=True,
                                   stdout=subprocess.PIPE).communicate()
            pids = res[0].split('\n')
            for pid in pids:
                if pid.strip() != '':
                    os.kill(int(pid.strip()), signal.SIGTERM)
            return

        pids = subprocess.Popen(['pidof', binaryPath],
                                stdout=subprocess.PIPE).communicate()
        for pid in pids[0].strip().split():
            os.kill(int(pid), signal.SIGTERM)
Beispiel #8
0
    def __init__(self, username=None, password="", host="localhost", port=3306, compression=False, use_tunnel=False, tunnel_username=None, tunnel_password=None, tunnel_port=22):
        if username is None:
            try:
                self.username = os.getlogin()
            except:
                self.username = ""
        else:
            self.username = username

        self.password = password
        self.host = host
        self.port = port
        self.compression = compression
        self.use_tunnel = use_tunnel

        if use_tunnel and tunnel_username is None:
            try:
                tunnel_username = os.getlogin()
            except:
                tunnel_username = ""

        self.tunnel_username = tunnel_username
        self.tunnel_password = tunnel_password
        self.tunnel_port = tunnel_port

        self.async_queries = []
def main():
    args = parser.parse_args()
 
    # Retrieve the right number of lines
    try:
        nodesFile = open(args.nodes_address_file)
        nodesInfos = [line for line in nodesFile]
    except IOError as e:
       print "I/O error({0}) on "+args.nodes_address_file+": {1}".format(e.errno, e.strerror)
       sys.exit()
    
    hosts  = [s.strip().split(':')[0] for s in nodesInfos]
    hosts.append(args.service_node)
    frontends = list(set([str('frontend.'+get_host_site(h)) for h in hosts]))
    

    ## Remove the old DHT-EXP hierarchy 
    logger.info('Remove old files on each NFS server involved in the experiment ('+str(frontends)+')')
    whoami=os.getlogin()
    cmd = 'rm -rf ~/SLOTH-EXP-TMP' 
    TaktukRemote(cmd, frontends, connection_params={'user': str(whoami)}).run()


    ## Copy the DHT-EXP hierarchy to the remote site
    logger.info('Copy sloth and injector files on each NFS server involved in the experiment ('+str(frontends)+')')
    TaktukRemote('mkdir ~/SLOTH-EXP-TMP/', frontends, connection_params={'user': str(whoami)}).run()
    TaktukPut(frontends, ['SLOTH_HOME'],'/home/'+str(os.getlogin())+'/SLOTH-EXP-TMP/.', connection_params={'user': str(whoami)}).run()
    TaktukPut(frontends, ['INJECTOR_HOME'],'/home/'+str(os.getlogin())+'/SLOTH-EXP-TMP/.', connection_params={'user': str(whoami)}).run()
    TaktukPut(frontends,  ['peers.info'], '/tmp/'+str(os.getlogin())+'-peers.info', connection_params={'user': str(whoami)}).run()


    test = TaktukPut(frontends, ['' ], connection_params={'user': str(whoami)}).run()
def getUsername():
    """
    Figure out what the current username is in the form "Richard West <*****@*****.**>"
    
    It should be in the format "Richard West <*****@*****.**>". We do this by
    interrogating git, if possible
    """
    name = ''
    email = ''
    try:
        p=subprocess.Popen('git config --get user.name'.split(),
                stdout=subprocess.PIPE)
        name = p.stdout.read()
    except OSError:
        pass
    if name:
        name = name.strip()
    else:
        print "Couldn't find user.name from git."
        name = os.getlogin()
    
    try:
        p=subprocess.Popen('git config --get user.email'.split(),
                stdout=subprocess.PIPE)
        email = p.stdout.read()
    except OSError:
        pass
    if email:
        email = email.strip()
    else:
        print "Couldn't find user.email from git."
        email = os.getlogin() + "@" + os.uname()[1]
    
    return '{0} <{1}>'.format(name,email)
	def get(self):
		os.system("mkdir /home/"+os.getlogin()+"/Public/C")
		os.system("mkdir /home/"+os.getlogin()+"/Public/C++")
		os.system("mkdir /home/"+os.getlogin()+"/Public/Java")
		os.system("mkdir /home/"+os.getlogin()+"/Public/Ruby")
		os.system("mkdir /home/"+os.getlogin()+"/Public/Python")								
		self.render("login.html");
Beispiel #12
0
def recursive_chown(path, uid, gid):
    """Emulates 'chown -R *uid*:*gid* *path*' in pure Python"""
    error_msg = _(
        "Error: Gate One does not have the ability to recursively chown %s to "
        "uid %s/gid %s.  Please ensure that user, %s has write permission to "
        "the directory.")
    try:
        os.chown(path, uid, gid)
    except OSError as e:
        if e.errno in [errno.EACCES, errno.EPERM]:
            raise ChownError(error_msg % (path, uid, gid, repr(os.getlogin())))
        else:
            raise
    for root, dirs, files in os.walk(path):
        for momo in dirs:
            _path = os.path.join(root, momo)
            try:
                os.chown(_path, uid, gid)
            except OSError as e:
                if e.errno in [errno.EACCES, errno.EPERM]:
                    raise ChownError(error_msg % (
                        _path, uid, gid, repr(os.getlogin())))
                else:
                    raise
        for momo in files:
            _path = os.path.join(root, momo)
            try:
                os.chown(_path, uid, gid)
            except OSError as e:
                if e.errno in [errno.EACCES, errno.EPERM]:
                    raise ChownError(error_msg % (
                        _path, uid, gid, repr(os.getlogin())))
                else:
                    raise
Beispiel #13
0
	def createDocumentProperties(self):
		'''This method is used to create document properties element int XMLSS
			 like Author, Created Date,Company Name,Last Modified Date
		'''
		workbookElem = self._xmlssDoc.getroot()
		docPropElem = etree.Element(etree.QName(self._xmlssNameSpaceMap["o"],"DocumentProperties"),xmlns = self._xmlnsO)
		temp=etree.Element(etree.QName(self._xmlssNameSpaceMap["o"],"Author"))
		temp.text = os.getlogin()
		docPropElem.append(temp)
		temp=etree.Element(etree.QName(self._xmlssNameSpaceMap["o"],"LastAuthor"))
		temp.text = os.getlogin()
		docPropElem.append(temp)
		temp=etree.Element( etree.QName(self._xmlssNameSpaceMap["o"],"Created"))
		p = subprocess.Popen(['date','+\"%a %B %d %H:%M:%S %Z %Y\"'],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
		curDate,err = p.communicate()
		temp.text = curDate.strip() 
		docPropElem.append(temp)
		temp=etree.Element(etree.QName(self._xmlssNameSpaceMap["o"],"LastSaved"))
		temp.text = curDate.strip() 
		docPropElem.append(temp)
		temp=etree.Element(etree.QName(self._xmlssNameSpaceMap["o"],"Company"))
		temp.text = os.getenv("COMPANYNAME")
		docPropElem.append(temp)
		temp=etree.Element(etree.QName(self._xmlssNameSpaceMap["o"],"Version"))
		temp.text ="12.00" 
		docPropElem.append(temp)
		workbookElem.append(docPropElem)
Beispiel #14
0
def send_envelope():
    envelope = Envelope(
        from_addr='%s@localhost' % os.getlogin(),
        to_addr='%s@localhost' % os.getlogin(),
        subject='Envelopes in Celery demo',
        text_body="I'm a helicopter!"
    )
    envelope.send('localhost', port=1025)
Beispiel #15
0
	def delMemo(self, id):
		if id == "ALL":
			self.database.execute("DELETE FROM "+os.getlogin()+" WHERE id;")
		else:
			self.database.execute("DELETE FROM "+os.getlogin()+" WHERE id=:id;", {
					"id":id})
		self.databaseConnection.commit()
		
Beispiel #16
0
 def getIdentifierInRealm(self, realm):
     # Nb, lack of realm spec means .*  (No means yes)
     if not self.realms:
         return os.getlogin()
     for realmSpec in self.realms:
         if "realm" not in realmSpec or realmSpec["realm"].match(realm):
             return realmSpec.get("id") or os.getlogin()
     return None
Beispiel #17
0
def os_08():
    # TBD: setuid
    os.getlogin() == 'gulan'
    pwd.getpwuid(os.getuid()) == 'gulan'
    # Note: os.environ is an dict-like instance of _Environ.
    os.environ['USER'] == 'gulan'
    os.environ['LOGNAME'] == 'gulan'
    print 'os_08 ok'
Beispiel #18
0
 def seteugid_to_login():
     """set effective user id and effective group id to the user and group ids
        of the user logged into this terminal."""
     uid = pwd.getpwnam(os.getlogin())[2]  # search /etc/passwd for uid and
     gid = pwd.getpwnam(os.getlogin())[3]  # gid of user logged into this
                                           # terminal.
     os.setegid(gid)
     os.seteuid(uid)                       # Is there a better way? --Dave
Beispiel #19
0
	def checkDatabase(self):
		try:
			self.database.execute("SELECT * FROM "+os.getlogin()+";")
		except sqlite3.OperationalError:
		# Table does not exist for this user, so create one.
			self.database.execute(
				"CREATE TABLE "+os.getlogin()+" (id INTEGER PRIMARY KEY, unread INTEGER, "\
				"sender TEXT, content TEXT, timestamp INTEGER);")
			self.databaseConnection.commit()
	def defaultInit(self):
		'''initialize output path with default value'''
		
		if not os.path.exists('/home/'+os.getlogin()+'/.BlenderRenderManager/render'):
			os.mkdir('/home/'+os.getlogin()+'/.BlenderRenderManager/render')
		self.path = '/home/'+os.getlogin()+'/.BlenderRenderManager/render/'
		self.pattern = 'N/S/M/V/L/F'
		self.overwrite = False
		self.backupLimit = 5
Beispiel #21
0
def post_mail():
    envelope = Envelope(from_addr='%s@localhost' % os.getlogin(),
                        to_addr='%s@localhost' % os.getlogin(),
                        subject='Envelopes in Flask demo',
                        text_body="I'm a helicopter!")

    smtp = envelopes.connstack.get_current_connection()
    smtp.send(envelope)

    return jsonify(dict(status='ok'))
Beispiel #22
0
 def get_abspath(self, dir):
     """
     get absolute path: ./ ../ ~/ / ~ --->/somepath/
     """
     if dir.startswith('./'):
         current_dir = self.current_dir[-1]
         current_dir = current_dir[:current_dir.rfind('/')+1]
         dir = dir.replace("./", current_dir)
     elif dir.startswith('ftp://'):
         if dir[6] == '.' or dir[6] == '~':
             dir = self.get_abspath(dir[6:])
         else:
             dir = dir[6:]
         index = dir.find('/')
         dir = 'hostname: ' + dir[:index] + '\tdirectory: ' + dir[index:]
     elif dir.startswith('http://'):
         if dir[7] == '.' or dir[7] == '~':
             dir = self.get_abspath(dir[7:])
         else:
             dir = dir[7:]
         index = dir.rfind('/')
         dir = 'hostname: ' + dir[:index] + '\tdirectory: ' + dir[index:]
     elif dir.startswith('/'):
         pass
     elif dir.startswith('~'):
         dir = dir.replace('~', '/home/'+os.getlogin())
     elif dir.startswith('../'):
         current_dir = self.current_dir[-1][:-1]
         temp_dir = dir
         while temp_dir.startswith('../'):
             current_dir = current_dir[:current_dir.rfind('/')]
             temp_dir = temp_dir[3:]
         dir = current_dir+'/'+temp_dir
     elif dir == '':
         #empty path
         dir = '/home/'+os.getlogin()
     else:
         #such as: cd somepath
         dir = self.current_dir[-1] + dir
     #check some special cases
     if dir.find('/./') != -1:
         dir = dir.replace('/./', '/')
     elif dir.find('//') != -1:
         dir = dir.replace('//', '/')
     dot_dot_index = dir.find('/../')
     while dot_dot_index != -1:
         first_path = dir[:dir[:dot_dot_index].rfind('/')]
         second_path = dir[dot_dot_index+4:]
         dir = first_path+'/'+second_path
         dot_dot_index = dir.find('/../')
     #dir always ends with '/'
     if dir[-1] != '/':
         return dir+'/'
     else:
         return dir
Beispiel #23
0
    def _cache_auth_token(self, token_obj):
        """
        Cache auth token in the config directory.

        :param token_obj: Token object.
        :type token_obj: ``object``
        """
        if not os.path.isdir(ST2_CONFIG_DIRECTORY):
            os.makedirs(ST2_CONFIG_DIRECTORY, mode=0o2770)
            # os.makedirs straight up ignores the setgid bit, so we have to set
            # it manually
            os.chmod(ST2_CONFIG_DIRECTORY, 0o2770)

        username = token_obj.user
        cached_token_path = self._get_cached_token_path_for_user(username=username)

        if not os.access(ST2_CONFIG_DIRECTORY, os.W_OK):
            # We don't have write access to the file with a cached token
            message = ('Unable to write token to "%s" (user %s doesn\'t have write '
                       'access to the parent directory). Subsequent requests won\'t use a '
                       'cached token meaning they may be slower.' % (cached_token_path,
                                                                     os.getlogin()))
            self.LOG.warn(message)
            return None

        if os.path.isfile(cached_token_path) and not os.access(cached_token_path, os.W_OK):
            # We don't have write access to the file with a cached token
            message = ('Unable to write token to "%s" (user %s doesn\'t have write '
                       'access to this file). Subsequent requests won\'t use a '
                       'cached token meaning they may be slower.' % (cached_token_path,
                                                                     os.getlogin()))
            self.LOG.warn(message)
            return None

        token = token_obj.token
        expire_timestamp = parse_isotime(token_obj.expiry)
        expire_timestamp = calendar.timegm(expire_timestamp.timetuple())

        data = {}
        data['token'] = token
        data['expire_timestamp'] = expire_timestamp
        data = json.dumps(data)

        # Note: We explictly use fdopen instead of open + chmod to avoid a security issue.
        # open + chmod are two operations which means that during a short time frame (between
        # open and chmod) when file can potentially be read by other users if the default
        # permissions used during create allow that.
        fd = os.open(cached_token_path, os.O_WRONLY | os.O_CREAT, 0o660)
        with os.fdopen(fd, 'w') as fp:
            fp.write(data)
        os.chmod(cached_token_path, 0o660)

        self.LOG.debug('Token has been cached in "%s"' % (cached_token_path))
        return True
Beispiel #24
0
def get_home_dir():
    # This function exists because of some weirdness when running remotely.
    home_dir = os.path.expanduser('~')
    if os.path.exists(home_dir):
        return home_dir
    elif sys.platform=='linux2':
        home_dir = os.path.join('/home', os.getlogin())
    elif sys.platform=='darwin':
        home_dir==os.path.join('/Users', os.getlogin())
    assert os.path.exists(home_dir), 'The home directory "{}" seems not to exist.  This is odd, to say the least.'.format(home_dir)
    return home_dir
Beispiel #25
0
    def get_abspath(self, dir):
        """
        get absolute path: ./ ../ ~/ / ~ --->/somepath/
        """
        if dir.startswith("./"):
            current_dir = self.current_dir[-1]
            current_dir = current_dir[: current_dir.rfind("/") + 1]
            dir = dir.replace("./", current_dir)
        elif dir.startswith("ftp://"):
            if dir[6] == "." or dir[6] == "~":
                dir = self.get_abspath(dir[6:])
            else:
                dir = dir[6:]
            index = dir.find("/")
            dir = "hostname: " + dir[:index] + "\tdirectory: " + dir[index:]
        elif dir.startswith("http://"):
            if dir[7] == "." or dir[7] == "~":
                dir = self.get_abspath(dir[7:])
            else:
                dir = dir[7:]
            index = dir.rfind("/")
            dir = "hostname: " + dir[:index] + " directory: " + dir[index:]
        elif dir.startswith("/"):
            pass
        elif dir.startswith("~"):
            dir = dir.replace("~", "/home/" + os.getlogin())
        elif dir.startswith("../"):
            current_dir = self.current_dir[-1][:-1]
            temp_dir = dir
            while temp_dir.startswith("../"):
                current_dir = current_dir[: current_dir.rfind("/")]
                temp_dir = temp_dir[3:]
            dir = current_dir + "/" + temp_dir
        elif dir == "":
            # empty path
            dir = "/home/" + os.getlogin()
        else:
            # such as: cd somepath
            dir = self.current_dir[-1] + dir

        if dir.find("/./") != -1:
            dir = dir.replace("/./", "/")
        elif dir.find("//") != -1:
            dir = dir.replace("//", "/")
        dot_dot_index = dir.find("/../")
        while dot_dot_index != -1:
            first_path = dir[: dir[:dot_dot_index].rfind("/")]
            second_path = dir[dot_dot_index + 4 :]
            dir = first_path + "/" + second_path
            dot_dot_index = dir.find("/../")
        if dir[-1] != "/":
            return dir + "/"
        else:
            return dir
Beispiel #26
0
	def __init__(self):
	
		#print("rapidconnect")

		#rapid_exe = sublime.active_window().active_view().settings().get("RapidExe")
		settings = RapidSettings().getSettings()
		rapid_exe = settings["RapidExe"]

		if os.name == "nt":
			# check if rapid is already running	
			rapid_running = True
			rapid = subprocess.check_output("tasklist /FI \"IMAGENAME eq " + rapid_exe + ".exe\" /FO CSV")
			rapid_search = re.search(rapid_exe + ".exe", rapid.decode("ISO-8859-1"))
			if rapid_search == None:
				rapid_debug = subprocess.check_output("tasklist /FI \"IMAGENAME eq " + rapid_exe + "_d.exe\" /FO CSV")
				rapid_debug_search = re.search(rapid_exe + "_d.exe", rapid_debug.decode("ISO-8859-1"))
				if rapid_debug_search == None:
					rapid_running = False
			if rapid_running:
				return	
		elif os.name == "posix":
			data = subprocess.Popen(['ps','aux'], stdout=subprocess.PIPE).stdout.readlines() 
			rapid_running = False
			for line in data:
				lineStr = line.decode("utf-8")
				if lineStr.find(rapid_exe) > -1 and lineStr.find(os.getlogin()) > -1:
					print("Rapid executable is already running for user: "******"Host" in settings and settings["Host"] != "localhost":
			return

		if os.name == "nt":
			rapid_path = settings["RapidPathWin"]
		elif os.name == "posix":
			os.chdir(RapidSettings().getStartupProjectPath()) 
			rapid_path = os.path.realpath(settings["RapidPathOSX"])
		else:
			RapidOutputView.printMessage("Could not find \"RapidPath<OS>\" variable from projects' rapid_sublime -file!")
			return

		if rapid_path != None and rapid_exe != None:
			RapidOutputView.printMessage("Starting " + rapid_exe)
			full_path = os.path.abspath(os.path.join(rapid_path, rapid_exe))
			subprocess.Popen(full_path, cwd=rapid_path)
			if os.name == "posix":
				time.sleep(0.5) #small delay to get server running on OSX
		else:
			RapidOutputView.printMessage("Could not start server executable!")
			RapidOutputView.printMessage("\"RapidPath<OS>\" and/or \"RapidExe\" variables not found from \"Preferences.sublime_settings\" file!")
Beispiel #27
0
 def test_uses_getlogin(self):
     settings = {
         'host':'host-%d' % random.randint(1,100),
     }
     _mox = mox.Mox()
     _mox.StubOutWithMock(os, 'getlogin')
     random_user = '******' % random.randint(1,100)
     os.getlogin().AndReturn(random_user)
     _mox.ReplayAll()
     results = utils.get_clone_base_url(settings)
     self.assertEqual('%s@%s' % (random_user, settings['host']), results)
     _mox.UnsetStubs()
Beispiel #28
0
def install_file(config_file_name, target_dir, target_file_name = None):
    if target_file_name == None:
        target_file_name = config_file_name

    our = path.join(config_dir, config_file_name)
    target = path.join(target_dir, target_file_name)
    if target_file_name == '.gitconfig' and \
        (os.getlogin() != 'zapu' and os.getlogin() != 'Zapu'):
        print("Not installing {}, or are you really me?".format(target_file_name))
        return

    try_install_interactive(config_file_name, our, target)
Beispiel #29
0
 def test_getlogin_fails(self):
     settings = {
         'host':'host-%d' % random.randint(1,100),
     }
     _mox = mox.Mox()
     _mox.StubOutWithMock(os, 'getlogin')
     random_user = '******' % random.randint(1,100)
     os.getlogin().AndRaise(OSError)
     _mox.ReplayAll()
     results = utils.get_clone_base_url(settings)
     self.assertEqual('%s@%s' % (utils.DEFAULT_USER_NAME, settings['host']), results)
     _mox.UnsetStubs()
Beispiel #30
0
 def testBoolFlagCaseInsensitive(self):
   self.assertEqual('Hello %s.' % os.getlogin(),
                    commands.getoutput('./gflags_example '
                                       '--overwrite_name=T'))
   self.assertEqual('Hello %s.' % os.getlogin(),
                    commands.getoutput('./gflags_example '
                                       '--overwrite_name=Y'))
   self.assertEqual('Hello %s.' % os.getlogin(),
                    commands.getoutput('./gflags_example '
                                       '--overwrite_name=tRue'))
   self.assertEqual('Hello %s.' % os.getlogin(),
                    commands.getoutput('./gflags_example '
                                       '--overwrite_name=yEs'))
Beispiel #31
0
class lab2g(unittest.TestCase):
    """All test cases for lab2g - while loops & sys.argv & if statements"""
    def test_0(self):
        """[Lab 2] - [Investigation 3] - [Part 3] - while loops, sys.argv & if - Test for file creation: ./lab2g.py"""
        error_output = 'your file cannot be found (HINT: make sure your file are in the correct directory)'
        self.assertTrue(os.path.exists('./lab2g.py'), msg=error_output)

    def test_1(self):
        """[Lab 2] - [Investigation 3] - [Part 3] - while loops, sys.argv & if - Test for errors: ./lab2g.py"""
        # Run students program
        p = subprocess.Popen(['/usr/bin/python3', './lab2g.py'],
                             stdout=subprocess.PIPE,
                             stdin=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        stdout, err = p.communicate()
        # Fail test if process returns a no zero exit status
        return_code = p.wait()
        error_output = 'your program exited with an error(HINT: try running your program to see the error)'
        self.assertEqual(return_code, 0, msg=error_output)

    def test_2(self):
        """[Lab 2] - [Investigation 3] - [Part 3] - while loops, sys.argv & if - Test for correct shebang line: ./lab2g.py"""
        lab_file = open('./lab2g.py')
        first_line = lab_file.readline()
        lab_file.close()
        error_output = 'your script does not have a correct shebang line (HINT: what should the first line contain)'
        self.assertEqual(first_line.strip(),
                         '#!/usr/bin/env python3',
                         msg=error_output)

    @unittest.skipIf(os.getlogin() == 'travis', "disregarding username check")
    def test_3(self):
        """[Lab 2] - [Investigation 3] - [Part 3] - while loops, sys.argv & if - Test for user id: ./lab2g.py"""
        lab_file = open('./lab2g.py')
        all_lines = lab_file.readlines()
        lab_file.close()
        author_id = "not set"
        error_output = "Author ID not set in your script"
        for each_line in all_lines:
            if 'Author ID:' in each_line:
                author_id = each_line.strip().split(":")[1].replace(' ', '')
                error_output = "Author ID does not match user name running the CheckLab2 script"
        user_id = os.getlogin()
        self.assertEqual(author_id, user_id, msg=error_output)

    def test_4(self):
        """[Lab 2] - [Investigation 3] - [Part 3] - while loops, sys.argv & if - Test for errors: ./lab2g.py 5"""
        # Run students program
        p = subprocess.Popen(['/usr/bin/python3', './lab2g.py', '5'],
                             stdout=subprocess.PIPE,
                             stdin=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        stdout, err = p.communicate()
        # Fail test if process returns a no zero exit status
        return_code = p.wait()
        error_output = 'your script exited with an error (HINT: try running your program to see the error, careful not to mix up ints and strings)'
        self.assertEqual(return_code, 0, msg=error_output)

    def test_5(self):
        """[Lab 2] - [Investigation 3] - [Part 3] - while loops, sys.argv & if - Test for errors: ./lab2g.py 10"""
        # Run students program
        p = subprocess.Popen(['/usr/bin/python3', './lab2g.py', '10'],
                             stdout=subprocess.PIPE,
                             stdin=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        stdout, err = p.communicate()
        # Fail test if process returns a no zero exit status
        return_code = p.wait()
        error_output = 'your script exited with an error (HINT: try running your program to see the error, careful not to mix up ints and strings)'
        self.assertEqual(return_code, 0, msg=error_output)

    def test_6(self):
        """[Lab 2] - [Investigation 3] - [Part 3] - while loops, sys.argv & if - Test output with no arguments: ./lab2g.py"""
        # Run students program
        p = subprocess.Popen(['/usr/bin/python3', './lab2g.py'],
                             stdout=subprocess.PIPE,
                             stdin=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        stdout, err = p.communicate()
        # Fail test if output is different from expected_output
        expected_output = b'3\n2\n1\nblast off!\n'
        error_output = 'wrong output(HINT: should loop 3 times by default )'
        self.assertEqual(stdout, expected_output, msg=error_output)

    def test_7(self):
        """[Lab 2] - [Investigation 3] - [Part 3] - while loops, sys.argv & if - Test output with: ./lab2g.py 5"""
        # Run students program
        p = subprocess.Popen(['/usr/bin/python3', './lab2g.py', '5'],
                             stdout=subprocess.PIPE,
                             stdin=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        stdout, err = p.communicate()
        # Fail test if output is different from expected_output
        expected_output = b'5\n4\n3\n2\n1\nblast off!\n'
        error_output = 'wrong output(HINT: should loop 5 times.)'
        self.assertEqual(stdout, expected_output, msg=error_output)

    def test_8(self):
        """[Lab 2] - [Investigation 3] - [Part 3] - while loops, sys.argv & if - Test output with: ./lab2g.py 10"""
        # Run students program
        p = subprocess.Popen(['/usr/bin/python3', './lab2g.py', '10'],
                             stdout=subprocess.PIPE,
                             stdin=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        stdout, err = p.communicate()
        # Fail test if output is different from expected_output
        expected_output = b'10\n9\n8\n7\n6\n5\n4\n3\n2\n1\nblast off!\n'
        error_output = 'wrong output(HINT: should loop 10 times)'
        self.assertEqual(stdout, expected_output, msg=error_output)
Beispiel #32
0
    resultData = sourceData.groupBy(cols).count().filter("count>1")
    if (resultData.count() > 0):
        log.error("Duplicate records found, data placed at: " + config['test']['absoluteDuplicateCheckFileName'])
        writeToFile(resultData, config['test']['absoluteDuplicateCheckFileName'], 'csv')

def nullCheck(sourceData,config,log):
    cols = sourceData.columns
    for x in cols:
        if(sourceData.count() == sourceData.where(sourceData[x].isNull()).count()):
            log.error(x + " is null")


if __name__ =='__main__':
    configFileName = sys.argv[1]
    print(configFileName)
    config = getConfig(configFileName)
    log = getLogger(config['log']['fileName'])
    log.info("Data Sanity Check Started, executed by"+os.getlogin())
    spark = getSparkSession()
    sourceData = getSource(spark,log,config)
    if config['test']['duplicateCheck'] :
        duplicateCheck(sourceData,config,log)

    if config['test']['nullCheck'] :
        nullCheck(sourceData,config,log)

    if config['test']['absoluteDuplicateCheck'] :
        absoluteDuplicate(sourceData,config,log)

    log.info("Data Sanity check completed")
Beispiel #33
0
#!/usr/bin/python
import os

filepath = '/usr/local/etc/restricted_user/' + os.getlogin() + '.txt'

with open(filepath, 'r') as f:
    allowed_commands = f.readlines()

orig_cmd = os.environ['SSH_ORIGINAL_COMMAND']

if orig_cmd in allowed_commands:
    os.system(orig_cmd)
Beispiel #34
0
    def respond_via(self, sock):
        facts = {
            'os.name': os.name,
            'os.getpid': os.getpid(),
            'os.supports_bytes_environ': os.supports_bytes_environ,
            'os.getcwd': os.getcwd(),
            'os.cpu_count': os.cpu_count(),
            'os.sep': os.sep,
            'os.altsep': os.altsep,
            'os.extsep': os.extsep,
            'os.pathsep': os.pathsep,
            'os.defpath': os.defpath,
            'os.linesep': os.linesep,
            'os.devnull': os.devnull,
            'socket.gethostname': socket.gethostname(),
            'socket.gethostbyaddr': socket.gethostbyaddr(socket.gethostname()),
            'socket.has_ipv6': socket.has_ipv6,
            'sys.argv': sys.argv,
            'sys.base_exec_prefix': sys.base_exec_prefix,
            'sys.base_prefix': sys.base_prefix,
            'sys.byteorder': sys.byteorder,
            'sys.builtin_module_names': sys.builtin_module_names,
            'sys.exec_prefix': sys.exec_prefix,
            'sys.executable': sys.executable,
            'sys.flags': {
                'debug': sys.flags.debug,
                'inspect': sys.flags.inspect,
                'interactive': sys.flags.interactive,
                'optimize': sys.flags.optimize,
                'dont_write_bytecode': sys.flags.dont_write_bytecode,
                'no_user_site': sys.flags.no_user_site,
                'no_site': sys.flags.no_site,
                'ignore_environment': sys.flags.ignore_environment,
                'verbose': sys.flags.verbose,
                'bytes_warning': sys.flags.bytes_warning,
                'quiet': sys.flags.quiet,
                'hash_randomization': sys.flags.hash_randomization,
            },
            'sys.float_info': {
                'epsilon': sys.float_info.epsilon,
                'dig': sys.float_info.dig,
                'mant_dig': sys.float_info.mant_dig,
                'max': sys.float_info.max,
                'max_exp': sys.float_info.max_exp,
                'max_10_exp': sys.float_info.max_10_exp,
                'min': sys.float_info.min,
                'min_exp': sys.float_info.min_exp,
                'min_10_exp': sys.float_info.min_10_exp,
                'radix': sys.float_info.radix,
                'rounds': sys.float_info.rounds,
            },
            'sys.getallocatedblocks': sys.getallocatedblocks(),
            'sys.getdefaultencoding': sys.getdefaultencoding(),
            'sys.getfilesystemencoding': sys.getfilesystemencoding(),
            'sys.hash_info': {
                'width': sys.hash_info.width,
                'modulus': sys.hash_info.modulus,
                'inf': sys.hash_info.inf,
                'nan': sys.hash_info.nan,
                'imag': sys.hash_info.imag,
                'algorithm': sys.hash_info.algorithm,
                'hash_bits': sys.hash_info.hash_bits,
                'seed_bits': sys.hash_info.seed_bits,
            },
            'sys.hexversion': sys.hexversion,
            #'sys.long_info': sys.long_info, # deprecated in 3
            'sys.implementation': {
                'name': sys.implementation.name,
                'version': {
                    'major': sys.implementation.version.major,
                    'minor': sys.implementation.version.minor,
                    'micro': sys.implementation.version.micro,
                    'releaselevel': sys.implementation.version.releaselevel,
                    'serial': sys.implementation.version.serial,
                },
                'hexversion': sys.implementation.hexversion,
                'cache_tag': sys.implementation.cache_tag,
            },
            'sys.int_info': {
                'bits_per_digit': sys.int_info.bits_per_digit,
                'sizeof_digit': sys.int_info.sizeof_digit,
            },
            #'sys.maxint': sys.maxint, # deprecated in 3
            'sys.maxsize': sys.maxsize,
            'sys.maxunicode': sys.maxunicode,
            'sys.modules': list(sys.modules.keys()),
            'sys.path': sys.path,
            'sys.platform': sys.platform,
            'sys.prefix': sys.prefix,
            'sys.thread_info': {
                'name': sys.thread_info.name,
                'lock': sys.thread_info.lock,
                'version': sys.thread_info.version,
            },
            'sys.version': sys.version,
            'sys.api_version': sys.api_version,
            'sys.version_info': {
                'major': sys.version_info.major,
                'minor': sys.version_info.minor,
                'micro': sys.version_info.micro,
                'releaselevel': sys.version_info.releaselevel,
                'serial': sys.version_info.serial,
            },
        }

        facts['os.environ'] = {k: v for (k, v) in os.environ.items()}

        # Availability: Windows
        if sys.platform.startswith('win') or sys.platform.startswith('cygwin'):
            facts['os.getlogin'] = os.getlogin()
            facts['os.getpid'] = os.getpid()
            facts['os.getppid'] = os.getppid()

            winver = sys.getwindowsversion()
            facts['sys.getwindowsversion'] = {
                'major': winver.major,
                'minor': winver.minor,
                'build': winver.build,
                'platform': winver.platform,
                'service_pack': winver.service_pack,
                'service_pack_minor': winver.service_pack_minor,
                'service_pack_major': winver.service_pack_major,
                'suite_mask': winver.suite_mask,
                'product_type': winver.product_type,
            }
            facts['sys.dllhandle'] = sys.dllhandle

        # # Availability: Unix/POSIX
        # # we're assuming Unix == POSIX for this purpose
        # if sys.platform.startswith('linux') or sys.platform.startswith('freebsd') or sys.platform.startswith('darwin'):
        #     facts['sys.abiflags'] = sys.abiflags
        #     facts['os.getegid'] = os.getegid()
        #     facts['os.geteuid'] = os.geteuid()
        #     facts['os.getgid'] = os.getgid()
        #     facts['os.getgroups'] = os.getgroups()
        #     facts['os.getlogin'] = os.getlogin()
        #     facts['os.getpgid'] = os.getpgid()
        #     facts['os.getpgrp'] = os.getpgrp()
        #     facts['os.getpid'] = os.getpid()
        #     facts['os.getppid'] = os.getppid()
        #     facts['os.getpriority'] = os.getpriority()
        #     facts['os.getresuid'] = os.getresuid()
        #     facts['os.getresgid'] = os.getresgid()
        #     facts['os.getuid'] = os.getuid()
        #     facts['os.getloadavg'] = os.getloadavg()
        #     facts['os.uname'] = os.uname()
        #
        #     facts['socket.if_nameindex'] = socket.if_nameindex()
        #     facts['sys.getdlopenflags'] = sys.getdlopenflags()

        resp = FactsResponseMessage(facts)
        resp.send_via(sock)
Beispiel #35
0
def store_2ddata(data,
                 fname,
                 pltitle='',
                 dir='./',
                 fits=False,
                 plot=True,
                 plrange=(None, None),
                 log=False,
                 rollaxes=False,
                 cmap='RdYlBu',
                 xlab='X [pix]',
                 ylab='Y [pix]',
                 cbarlab=None,
                 hdr=(),
                 ident=True):
    """
	Store **data** to disk as FITS and/or plot as annotated plot in PDF.

	@param [in] data 2D data array to show
	@param [in] fname Filename base to use (also fallback for plot title)
	@param [in] pltitle Plot title (if given)
	@param [in] dir Output directory
	@param [in] fits Toggle FITS output
	@param [in] plot Toggle 2D plot output as PDF
	@param [in] plrange Use this range for plotting in imshow() (None for autoscale)
	@param [in] log Take logarithm of data before storing.
	@param [in] rollaxes Roll axes for PDF plot such that (0,0) is the center
	@param [in] cmap Colormap to use for PDF
	@param [in] xlab X-axis label
	@param [in] ylab Y-axis label
	@param [in] cbarlab Colorbar label (for units)
	@param [in] hdr Additional FITS header items, give a list of tuples: [(key1, val1), (key2, val2)]
	@param [in] ident Add identification string to plots
	@returns Tuple of (fitsfile path, plotfile path)
	"""

    # Do not store empty data
    if (len(data) <= 0):
        return

    data_arr = np.asanyarray(data)
    if (log):
        data_arr = np.log10(data_arr)
    extent = None
    if (rollaxes):
        sh = data_arr.shape
        extent = (-sh[1] / 2., sh[1] / 2., -sh[0] / 2., sh[0] / 2.)

    # Check if dir exists, or create
    if (not os.path.isdir(dir)):
        os.makedirs(dir)

    fitsfile = filenamify(fname) + '.fits'
    fitspath = os.path.join(dir, fitsfile)
    plotfile = filenamify(fname) + '.pdf'
    plotpath = os.path.join(dir, plotfile)

    if (fits):
        # Generate some metadata. Also store plot settings here
        hdr_dict = dict({
            'filename': fitsfile,
            'desc': fname,
            'title': pltitle,
            'plxlab': xlab,
            'plylab': ylab,
            'pllog': log,
            'plrlxs': rollaxes,
            'plcmap': cmap,
            'plrng0': plrange[0] if plrange[0] else 0,
            'plrng1': plrange[1] if plrange[1] else 0,
        }.items() + dict(hdr).items())
        hdr = mkfitshdr(hdr_dict)
        # Store data to disk
        pyfits.writeto(fitspath,
                       data_arr,
                       header=hdr,
                       clobber=True,
                       checksum=True)

    if (plot):
        #plot_from_fits(fitspath)
        pltit = fname
        if (pltitle):
            pltit = pltitle

        # Plot without GUI, using matplotlib internals
        fig = Figure(figsize=(6, 6))
        ax = fig.add_subplot(111)
        # Make margin smaller
        fig.subplots_adjust(left=0.15, right=0.95, top=0.9, bottom=0.1)
        img = 0
        # Colormaps
        # plus min: cmap=cm.get_cmap('RdYlBu')
        # linear: cmap=cm.get_cmap('YlOrBr')
        # gray: cmap=cm.get_cmap('gray')
        img = ax.imshow(data_arr,
                        interpolation='nearest',
                        cmap=cm.get_cmap(cmap),
                        aspect='equal',
                        extent=extent,
                        vmin=plrange[0],
                        vmax=plrange[1])
        ax.set_title(pltit)
        ax.set_xlabel(xlab)
        ax.set_ylabel(ylab)
        # dimension 0 is height, dimension 1 is width
        # When the width is equal or more than the height, use a horizontal bar, otherwise use vertical
        if (data_arr.shape[0] / data_arr.shape[1] >= 1.0):
            cbar = fig.colorbar(img,
                                orientation='vertical',
                                aspect=30,
                                pad=0.05,
                                shrink=0.8)
        else:
            cbar = fig.colorbar(img,
                                orientation='horizontal',
                                aspect=30,
                                pad=0.12,
                                shrink=0.8)
        if (cbarlab):
            cbar.set_label(cbarlab)

        # Add ID string
        if (ident):
            # Make ID string
            datestr = datetime.datetime.utcnow().isoformat() + 'Z'
            # Put this in try-except because os.getlogin() fails in screen(1)
            try:
                idstr = "%s@%s %s %s" % (os.getlogin(), os.uname()[1], datestr,
                                         sys.argv[0])
            except OSError:
                idstr = "%s@%s %s %s" % (getpass.getuser(), os.uname()[1],
                                         datestr, sys.argv[0])

            ax.text(0.01, 0.01, idstr, fontsize=7, transform=fig.transFigure)

        canvas = FigureCanvas(fig)
        #canvas.print_figure(plotfile, bbox_inches='tight')
        canvas.print_figure(plotpath)

    return (fitspath, plotpath)
# -*- coding: utf-8 -*-
"""
Created on Mon Jun  4 11:56:36 2018

@author: Timothy_Richards

Description:
"""
#Program to monitor QA of flux system. Email status every Monday morning.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import os
from datetime import datetime,timedelta

username1 = os.getlogin()

data = pd.read_csv('C://Users/'+username1+'/Dropbox/Obrist Lab/Tekran/Raw Data/2537B_Gradient/HgQADataSet.csv')

data['datetime'] = pd.to_datetime(data['datetime'],yearfirst=True)
data = data.set_index('datetime')
data.index = pd.to_datetime(data.index)

#Slice dataframe to use only last 30 days
today = pd.datetime.today().date()
cut_off = pd.to_datetime(today - pd.offsets.Day(29))
data = data[cut_off:]
#%%
#Was going to make this a function, but can't figure out how to return dataframe correctly
#Calculate RPD for both inlets, Tekran B
timespan = timedelta(minutes = 90)
Beispiel #37
0
def get_current_user(space):
    """ Gets the name of the owner of the current PHP script"""
    return space.newstr(os.getlogin())
Beispiel #38
0
PYTHON:  3.6.1

Please enter your gmail login and password before using script
(login, password, login again)

'''

import os
import string
import shutil
import socket
import smtplib
from bs4 import BeautifulSoup  # BS and urllib to get IP on interne.yandex.ru
from urllib.request import urlopen

LOGIN = os.getlogin()
FILES = []
INFO = str(os.environ)


# Checking available disks for infection (disk C does not give rights)
def check_disk():
    for letter in 'CDEFGHIJKLMNOPQRSTUVWXYZ':
        path = letter + '://'
        try:
            if os.path.isdir(path):
                shutil.copy('INTERNALDEMON.py', path)
            else:
                pass
        except PermissionError:
            pass
Beispiel #39
0
Estudando

@author: josez
"""
# %%

from statsmodels.tsa.stattools import grangercausalitytests
import pandas as pd
import itertools
import subprocess
from comtypes import COMError
import pyeviews as evp
import re
import os
USER = os.getlogin()
GLOBALEVAPP = None

# %% Box Jenkins


def _GetApp(app=None):
    global GLOBALEVAPP
    if app is not None:
        return app
    if GLOBALEVAPP is None:
        globalevapp = evp.GetEViewsApp(instance='new', showwindow=True)
    return globalevapp


def gridsearch_box_jenkins_eviews(y,
Beispiel #40
0
def getlogin():
    try:
        return os.getlogin()
    except Exception:
        return os.environ['USER']
Beispiel #41
0
     "-s",
     "--samples",
     dest="samples",
     action="callback",
     callback=Load(),
     type="string",
     default={},
     help="load samples from JSON file",
 ),
 make_option(
     "-o",
     "--outputPath",
     dest="outputPath",
     action="store",
     type="string",
     default="/store/group/phys_higgs/cmshgg/%s/flashgg" % os.getlogin(),
     help="output storage path. default: %default",
 ),
 make_option(
     "-d",
     "--task-dir",
     dest="task_dir",
     action="store",
     type="string",
     default=None,
     help="task folder. default: same as campaign",
 ),
 make_option(
     "-C",
     "--campaign",
     dest="campaign",
Beispiel #42
0
from shutil import copyfile


def get_dep(module):
    cmd = 'yes | /usr/bin/python3 -m pip install %s >> /dev/null' % module
    os.system(cmd)


try:
    from pynput.keyboard import Listener
except ModuleNotFoundError:
    get_dep('pynput')
    print('error import pnput')
    pass

username = os.getlogin()
logging_file = f"logging"
if not os.path.isdir('.logging'):
    os.mkdir('.logging')
if not os.path.isfile(os.getcwd() + '/.logging/keystrokes.txt'):
    msg = ('Logging Keystrokes of user: %s\n' % username)
    open(os.getcwd() + '/.logging/keystrokes.txt', 'wb').write(msg.encode())


def keyhandler(key):
    try:
        letter = key.char
        open(os.getcwd() + '/.logging/keystrokes.txt', 'a').write(key.char)
    except AttributeError:
        # it's a special character
        if str(key) == 'Key.space':
Beispiel #43
0
import shutil
import getpass
import warnings
from datetime import datetime as dt
from selenium import webdriver
from selenium.webdriver.common.keys import Keys as keys
from selenium.webdriver.support.select import Select
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException

DRIVER_PATH = '../driver/chromedriver'
DefaultFileName = 'kakuteiSeisekiCsv.csv'
NUWEB = 'https://nuweb.nagasaki-u.ac.jp/'
VCONN = 'https://v-conn.nagasaki-u.ac.jp'
DL_DIR = '/Users/' + os.getlogin() + '/Downloads/'
WAIT_TIME = 5


# Log color setting
class pycolor:
    BLACK = '\033[30m'
    RED = '\033[31m'
    GREEN = '\033[32m'
    YELLOW = '\033[33m'
    BLUE = '\033[34m'
    PURPLE = '\033[35m'
    CYAN = '\033[36m'
    WHITE = '\033[37m'
    END = '\033[0m'
    BOLD = '\038[1m'
        'NAME':
        'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME':
        'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME':
        'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# TTKD Directories
USER_FILES_DIR = os.path.join(os.path.join('C:/Users', os.getlogin()), 'ttkd')
BACKUP_FILES_DIR = os.path.join(USER_FILES_DIR, 'backups')
PICTURES_DIR = os.path.join(USER_FILES_DIR, 'pictures')
Beispiel #45
0
    auxmonth = (int)(DateMin[5:7])
    auxyear = (int)(DateMin[:4])

    for i in range(binsplt):
        auxmonth = auxmonth + 1
        if auxmonth == 13:
            auxmonth = 1
            auxyear = auxyear + 1
        binString = (str)(auxyear) + '-' + "{0:0=2d}".format(auxmonth)
        binspltStrings.append(binString)

    exdf.Updated = pd.to_datetime(exdf['Updated'])

    plt.hist(exdf['Updated'], bins=binsplt)
    plt.xlabel('Months')
    plt.ylabel('Amount of issues')
    plt.title('Amount of solved issues by month')
    plt.xticks(binspltStrings, binspltStrings)
    plt.xticks(rotation=60)
    plt.show()


if __name__ == "__main__":
    print('Start')
    columnvalues = ['Issue Type', 'Issue key', 'Summary', 'Assignee', 'Reporter', 'Updated']
    target = FileFinder()
    cleaneddf = DataFrameCleaner(target, columnvalues)
    exceldf = os.path.join('C:\\', 'Users', os.getlogin(), 'Downloads','JiraTickets.csv')
    #ExcelAppender(cleaneddf, exceldf)
    IssuesPlotter(cleaneddf)
Beispiel #46
0
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 15 09:29:36 2020

@author: Laptop
"""
import pickle
import flask
import os

print("Load model . . .")
mapGebruikers = "C:\\Users\\"
mapGebruiker = os.getlogin()
mapTM = r'\Documents\Github\DS\Hessel, TextMining 1'
hoofdmap = "%s%s%s" %(mapGebruikers, mapGebruiker, mapTM)
os.chdir(hoofdmap)

app = flask.Flask(__name__)
port=int(os.getenv("PORT",9099))

# model = pickle.load(open(r'data/optimodel_SVM_SL_KOD.pck', 'rb'))

@app.route('/predict', methods=['POST'])
def predict():
    features = flask.request.get_json(force=True)['features']
    prediction = 5
#   prediction_proba = model.predict_proba([features])[0,0]
    response = {'prediction': prediction}
        
    return flask.jsonify(response)
Beispiel #47
0
import os
import sys
import shlex
import signal
import writeLog
import Command
from Error_handle import Error_handle

SHELL_STATUS_RUN = 0
SHELL_STATUS_STOP = 1

EXECUTE_QUIT = False
EXECUTE_NONE = False

MAX_CMD_HISTORYLINE = 1000
USER_HOME = "/home/" + os.getlogin()
CMD_HISTORY_FILE = USER_HOME + "/.shell_history"
CMD_ALIASES = USER_HOME + "/.shell_aliases"

BACKGROUND = False

LAST_PID = 0


def handle_signal(signum, frame):
    """

    :param signum:
    :param frame:
    :return:
    """
Beispiel #48
0
def collect_os(info_add):
    import os

    def format_attr(attr, value):
        if attr in ('supports_follow_symlinks', 'supports_fd',
                    'supports_effective_ids'):
            return str(sorted(func.__name__ for func in value))
        else:
            return value

    attributes = (
        'name',
        'supports_bytes_environ',
        'supports_effective_ids',
        'supports_fd',
        'supports_follow_symlinks',
    )
    copy_attributes(info_add, os, 'os.%s', attributes, formatter=format_attr)

    for func in (
        'cpu_count',
        'getcwd',
        'getegid',
        'geteuid',
        'getgid',
        'getloadavg',
        'getresgid',
        'getresuid',
        'getuid',
        'uname',
    ):
        call_func(info_add, 'os.%s' % func, os, func)

    def format_groups(groups):
        return ', '.join(map(str, groups))

    call_func(info_add, 'os.getgroups', os, 'getgroups', formatter=format_groups)

    if hasattr(os, 'getlogin'):
        try:
            login = os.getlogin()
        except OSError:
            # getlogin() fails with "OSError: [Errno 25] Inappropriate ioctl
            # for device" on Travis CI
            pass
        else:
            info_add("os.login", login)

    # Environment variables used by the stdlib and tests. Don't log the full
    # environment: filter to list to not leak sensitive information.
    #
    # HTTP_PROXY is not logged because it can contain a password.
    ENV_VARS = frozenset((
        "APPDATA",
        "AR",
        "ARCHFLAGS",
        "ARFLAGS",
        "AUDIODEV",
        "CC",
        "CFLAGS",
        "COLUMNS",
        "COMPUTERNAME",
        "COMSPEC",
        "CPP",
        "CPPFLAGS",
        "DISPLAY",
        "DISTUTILS_DEBUG",
        "DISTUTILS_USE_SDK",
        "DYLD_LIBRARY_PATH",
        "ENSUREPIP_OPTIONS",
        "HISTORY_FILE",
        "HOME",
        "HOMEDRIVE",
        "HOMEPATH",
        "IDLESTARTUP",
        "LANG",
        "LDFLAGS",
        "LDSHARED",
        "LD_LIBRARY_PATH",
        "LINES",
        "MACOSX_DEPLOYMENT_TARGET",
        "MAILCAPS",
        "MAKEFLAGS",
        "MIXERDEV",
        "MSSDK",
        "PATH",
        "PATHEXT",
        "PIP_CONFIG_FILE",
        "PLAT",
        "POSIXLY_CORRECT",
        "PY_SAX_PARSER",
        "ProgramFiles",
        "ProgramFiles(x86)",
        "RUNNING_ON_VALGRIND",
        "SDK_TOOLS_BIN",
        "SERVER_SOFTWARE",
        "SHELL",
        "SOURCE_DATE_EPOCH",
        "SYSTEMROOT",
        "TEMP",
        "TERM",
        "TILE_LIBRARY",
        "TIX_LIBRARY",
        "TMP",
        "TMPDIR",
        "TRAVIS",
        "TZ",
        "USERPROFILE",
        "VIRTUAL_ENV",
        "WAYLAND_DISPLAY",
        "WINDIR",
        "_PYTHON_HOST_PLATFORM",
        "_PYTHON_PROJECT_BASE",
        "_PYTHON_SYSCONFIGDATA_NAME",
        "__PYVENV_LAUNCHER__",
    ))
    for name, value in os.environ.items():
        uname = name.upper()
        if (uname in ENV_VARS
           # Copy PYTHON* and LC_* variables
           or uname.startswith(("PYTHON", "LC_"))
           # Visual Studio: VS140COMNTOOLS
           or (uname.startswith("VS") and uname.endswith("COMNTOOLS"))):
            info_add('os.environ[%s]' % name, value)

    if hasattr(os, 'umask'):
        mask = os.umask(0)
        os.umask(mask)
        info_add("os.umask", '0o%03o' % mask)
import commands
import subprocess
import os, logging, sys, signal, time, shutil
import getpass

##################################################################################
# Variables
##################################################################################
userName = os.getlogin()
googleDriveDir = ""
gdfsInstaller = "/Library/Scripts/Workday/GoogleDriveFileStream.dmg"
# Logging File
#logFile = "/Library/Logs/Workday/googleDrive_Migration.log"
logFile = "/Users/" + userName + "/Library/Logs/Workday/googleDrive_Migration.log"
basedir = os.path.dirname(logFile)
if not os.path.exists(basedir):
    os.makedirs(basedir)
if not os.path.exists(logFile):
    with open(logFile, 'a'):
        os.utime(logFile, None)

logging.basicConfig(filename=logFile,
                    level=logging.DEBUG,
                    format='%(asctime)s - %(levelname)s: %(message)s')
# Console Handler
console = logging.StreamHandler()
console.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(message)s')
console.setFormatter(formatter)
logging.getLogger('').addHandler(console)
gstream = "/Applications/Google Drive File Stream.app"
Beispiel #50
0
import threading
import requests
import json
import signal
import time

sys.path.insert(0, os.path.dirname(__file__))

parser = argparse.ArgumentParser("python quickstart.py",
                                 description="Critic instance quick-start utility script.")
parser.add_argument("--quiet", action="store_true",
                    help="Suppress most output")
parser.add_argument("--testing", action="store_true",
                    help=argparse.SUPPRESS)

parser.add_argument("--admin-username", default=os.getlogin(),
                    help=argparse.SUPPRESS)
parser.add_argument("--admin-fullname", default=os.getlogin(),
                    help=argparse.SUPPRESS)
parser.add_argument("--admin-email", default=os.getlogin() + "@localhost",
                    help=argparse.SUPPRESS)
parser.add_argument("--admin-password", default="1234",
                    help=argparse.SUPPRESS)
parser.add_argument("--system-recipient", action="append",
                    help=argparse.SUPPRESS)

parser.add_argument("--state-dir", "-s",
                    help="State directory [default=temporary dir]")
parser.add_argument("--http-host", default="",
                    help="Hostname the HTTP server listens at [default=ANY]")
parser.add_argument("--http-port", "-p", default=8080, type=int,
Beispiel #51
0
                    help="Are to store files (default /data)")
parser.add_argument("-s",
                    "--selection",
                    type=str,
                    default="Dilepton",
                    help="Selection tier (default Dilepton)")
parser.add_argument("-d",
                    "--data_name",
                    type=str,
                    default="DibosonAnalysisData",
                    help="Data name")
parser.add_argument(
    "-u",
    "--username",
    type=str,
    default="%s" % os.getlogin(),
    help="Username for storage area, default is your login username")
parser.add_argument("--hadd",
                    action='store_true',
                    help="Combine files with hadd")
args = parser.parse_args()

if "store" in args.path[:7]:
    args.path = "/hdfs" + args.path
for directory in glob.glob(args.path):
    print "Copying directory", directory
    if not os.path.isdir(directory):
        print "Invalid filename: %s" % directory
        exit(1)
    dirs = directory.split("/")
    dir_name = dirs[-1]
Beispiel #52
0
#---------------------------------------------------------------#
## GenelDegiskenler
pencere_basligi = "@KekikAkademi UDEMY Kupon Çekme Aracı"       # Pencere Başlığımız
logo = '''
   _    _      _     _ _        _     _     _                   
  | |  / )    | |   (_) |      | |   | |   | |                  
  | | / / ____| |  _ _| |  _   | |   | | _ | | ____ ____  _   _ 
  | |< < / _  ) | / ) | | / )  | |   | |/ || |/ _  )    \| | | |
  | | \ ( (/ /| |< (| | |< (   | |___| ( (_| ( (/ /| | | | |_| |
  |_|  \_)____)_| \_)_|_| \_)   \______|\____|\____)_|_|_|\__  |
                                                         (____/   
'''                                                             # Logomuz
        # logo = http://patorjk.com/software/taag/#p=display&f=Doom&t=kopya%20Kagidi
#---------------------------------------------------------------#
try:
    kullanici_adi = os.getlogin()                                     # Kullanıcı Adı
except:
    import pwd
    kullanici_adi = pwd.getpwuid(os.geteuid())[0]                     # Kullanıcı Adı
bilgisayar_adi = platform.node()                                      # Bilgisayar Adı
oturum = kullanici_adi + "@" + bilgisayar_adi                         # Örn.: "kekik@Administrator"

isletim_sistemi = platform.system()                                        # İşletim Sistemi
bellenim_surumu = platform.release()                                       # Sistem Bellenim Sürümü
cihaz = isletim_sistemi + " | " + bellenim_surumu                          # Örn.: "Windows | 10"

tarih = datetime.datetime.now(pytz.timezone("Turkey")).strftime("%d-%m-%Y") # Bugünün Tarihi
saat = datetime.datetime.now(pytz.timezone("Turkey")).strftime("%H:%M")     # Bugünün Saati
zaman = tarih + " | " + saat

ip_req = requests.get('http://ip.42.pl/raw')    # Harici IP'yi bulmak için bir GET isteği yolluyoruz
Beispiel #53
0
def __init__(self):
    steamvr_dir = "C:\\Users\\" + os.getlogin(
    ) + "\\Documents\\steamvr\\input\\"
Beispiel #54
0
import os

path = os.getcwd()
print("path is:", path)

print(os.name)
print(os.getlogin())
print(os.getppid())

path = "/Users/ishantkumar/Downloads/orders.csv"
print("Is path exisiting: ", os.path.exists(path))
print("Is path a Drirectory: ", os.path.isdir(path))
print("Is path a File: ", os.path.isfile(path))

path = "/Users/ishantkumar/Downloads"

files = os.walk(path)
allFiles = list(files)  # Convert into a list
for file in allFiles:
    print(file)

# Assignment
# List all the files for Documents, Music and Videos
Beispiel #55
0
    def _get_username(self):
        username = os.environ.get('GNOME_ACCOUNT_NAME')
        if username is not None:
            return username

        return os.getlogin()
Beispiel #56
0
import os
import sys
import threading
import json
import random

try:
    unicode  # Python 2
except NameError:
    unicode = str  # Python 3

DEFAULT_FOLDER = '~/VLC_videos'
DOWNLOADS_FOLDER = '~/Downloads'

if sys.platform == "win32":  # for Windows
    DEFAULT_FOLDER = r'C:/Users/' + os.getlogin() + '/VLC_videos'
    DOWNLOADS_FOLDER = r'C:/Users/' + os.getlogin() + '/Downloads'


class Player(wx.Frame):
    """The main window has to deal with events.
    """
    def __init__(self, title):
        wx.Frame.__init__(self,
                          None,
                          -1,
                          title,
                          pos=wx.DefaultPosition,
                          size=(550, 500))

        # Menu Bar
Beispiel #57
0
    def run(self, task_id, resume_job=False, logging_thread=None):
        """
        This function is executed to run this job.

        :param int task_id:
        :param bool resume_job:
        :param sisyphus.worker.LoggingThread logging_thread:
        """

        logging.debug("Task name: %s id: %s" % (self.name(), task_id))
        job = self._job

        logging.info("Start Job: %s Task: %s" % (job, self.name()))
        logging.info("Inputs:")
        for i in self._job._sis_inputs:
            logging.info(str(i))

            # each input must be at least X seconds old
            # if an input file is too young it's may not synced in a network filesystem yet
            try:
                input_age = time.time() - os.stat(i.get_path()).st_mtime
                time.sleep(max(0, gs.WAIT_PERIOD_MTIME_OF_INPUTS - input_age))
            except FileNotFoundError:
                logging.warning('Input path does not exist: %s' % i.get_path())

            if i.creator and gs.ENABLE_LAST_USAGE:
                # mark that input was used
                try:
                    os.unlink(
                        os.path.join(i.creator, gs.JOB_LAST_USER,
                                     os.getlogin()))
                except OSError as e:
                    if e.errno not in (2, 13):
                        # 2: file not found
                        # 13: permission denied
                        raise e

                try:
                    user_path = os.path.join(i.creator, gs.JOB_LAST_USER,
                                             os.getlogin())
                    os.symlink(os.path.abspath(job._sis_path()), user_path)
                    os.chmod(user_path, 0o775)
                except OSError as e:
                    if e.errno not in (2, 13, 17):
                        # 2: file not found
                        # 13: permission denied
                        # 17: file exists
                        raise e

        tools.get_system_informations(sys.stdout)

        sys.stdout.flush()

        try:
            if resume_job:
                if self._resume is not None:
                    task = self._resume
                else:
                    task = self._start
                    logging.warning(
                        'No resume function set (changed tasks after job was initialized?) '
                        'Fallback to normal start function: %s' % task)
            else:
                task = self._start
            assert task is not None, "Error loading task"
            # save current directory and change into work directory
            with tools.execute_in_dir(self.path(gs.JOB_WORK_DIR)):
                f = getattr(self._job, task)

                # get job arguments
                for arg_id in self._get_arg_idx_for_task_id(task_id):
                    args = self._args[arg_id]
                    if not isinstance(args, (list, tuple)):
                        args = [args]
                    logging.info("-" * 60)
                    logging.info("Starting subtask for arg id: %d args: %s" %
                                 (arg_id, str(args)))
                    logging.info("-" * 60)
                    f(*args)
        except sp.CalledProcessError as e:
            if e.returncode == 137:
                # TODO move this into engine class
                logging.error(
                    "Command got killed by SGE (probably out of memory):")
                logging.error("Cmd: %s" % e.cmd)
                logging.error("Args: %s" % str(e.args))
                logging.error("Return-Code: %s" % e.returncode)
                logging_thread.out_of_memory = True
                logging_thread.stop()
            else:
                logging.error("Executed command failed:")
                logging.error("Cmd: %s" % e.cmd)
                logging.error("Args: %s" % str(e.args))
                logging.error("Return-Code: %s" % e.returncode)
                logging_thread.stop()
                self.error(task_id, True)
        except Exception as e:
            # Job failed
            logging.error("Job failed, traceback:")
            sys.excepthook(*sys.exc_info())
            logging_thread.stop()
            self.error(task_id, True)
            # TODO handle failed job
        else:
            # Job finished normally
            logging_thread.stop()
            if not self.continuable:
                self.finished(task_id, True)
            sys.stdout.flush()
            sys.stderr.flush()
            logging.info("Job finished successful")
Beispiel #58
0
file = open(base + 'run', 'w')

use_check = int(getParam(filename, "checkpoint", 0))
use_avail = int(getParam(filename, "use_available_checkpoints", 0))
use_check = (use_check == 1) or (use_avail == 1)

if use_check or use_avail:
    check_in = getParam(filename, "checkpoint_input_name", base[:-1])
    check_out = getParam(filename, "checkpoint_output_name", base[:-1])

    if use_check:
        print "Using checkpoint output directory: " + check_out
    if os.path.isdir(check_in) and use_avail:
        print "Using checkpoint  input directory: " + check_in

    temp_dir = "/scratch2/" + str(os.getlogin()) + "/" + check_out
    setParam(filename, "temp_dir", temp_dir, "checkpoint")
    print "Setting temp_dir: " + temp_dir
else:
    print "We are neither reading nor writing checkpoints."

debug = 0
#debug = 1

file.write("#!/bin/csh    \n")
file.write("#BSUB -J " + filename + " \n")
file.write("#BSUB -n " + str(processors) + " \n")
if debug == 1:
    file.write("#BSUB -I                         \n")
    file.write("#BSUB -W 0:30                    \n")
else:
Beispiel #59
0
def main():
    """main: parse args and create pipeline"""
    parser = argparse.ArgumentParser(
        description='Generate Concourse Pipeline utility',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )

    parser.add_argument(
        '-T',
        '--template',
        action='store',
        dest='template_filename',
        default="gpdb-tpl.yml",
        help='Name of template to use, in templates/'
    )

    default_output_filename = "gpdb_%s-generated.yml" % BASE_BRANCH
    parser.add_argument(
        '-o',
        '--output',
        action='store',
        dest='output_filepath',
        default=os.path.join(PIPELINES_DIR, default_output_filename),
        help='Output filepath to use for pipeline file, and from which to derive the pipeline name.'
    )

    parser.add_argument(
        '-O',
        '--os_types',
        action='store',
        dest='os_types',
        default=['centos7'],
        choices=['centos7', 'ubuntu18.04', 'win'],
        nargs='+',
        help='List of OS values to support'
    )

    parser.add_argument(
        '-t',
        '--pipeline_target',
        action='store',
        dest='pipeline_target',
        default='dev',
        help='Concourse target to use either: prod, dev, or <team abbreviation> '
             'where abbreviation is found from the team\'s ccp secrets file name ending.'
    )

    parser.add_argument(
        '-c',
        '--configuration',
        action='store',
        dest='pipeline_configuration',
        default='default',
        help='Set of platforms and test sections to use; only works with dev and team targets, ignored with the prod target.'
             'Valid options are prod (same as the prod pipeline), full (everything except release jobs), and default '
             '(follow the -A and -O flags).'
    )

    parser.add_argument(
        '-a',
        '--test_sections',
        action='store',
        dest='test_sections',
        choices=[
            'ICW',
            'Replication',
            'ResourceGroups',
            'Interconnect',
            'CLI',
            'UD',
            'AA',
            'Extensions'
        ],
        default=['ICW'],
        nargs='+',
        help='Select tests sections to run'
    )

    parser.add_argument(
        '-n',
        '--test_trigger_false',
        action='store_false',
        default=True,
        help='Set test triggers to "false". This only applies to dev pipelines.'
    )

    parser.add_argument(
        '-u',
        '--user',
        action='store',
        dest='user',
        default=os.getlogin(),
        help='Developer userid to use for pipeline name and filename.'
    )

    args = parser.parse_args()

    validate_target(args.pipeline_target)

    output_path_is_set = os.path.basename(args.output_filepath) != default_output_filename
    if (args.user != os.getlogin() and output_path_is_set):
        print("You can only use one of --output or --user.")
        exit(1)

    if args.pipeline_target == 'prod':
        args.pipeline_configuration = 'prod'

    if args.pipeline_configuration == 'prod' or args.pipeline_configuration == 'full':
        args.os_types = ['centos6', 'centos7', 'ubuntu18.04', 'win']
        args.test_sections = [
            'ICW',
            'Replication',
            'ResourceGroups',
            'Interconnect',
            'CLI',
            'UD',
            'Extensions'
        ]

    # if generating a dev pipeline but didn't specify an output,
    # don't overwrite the master pipeline
    if args.pipeline_target != 'prod' and not output_path_is_set:
        pipeline_file_suffix = suggested_git_branch()
        if args.user != os.getlogin():
            pipeline_file_suffix = args.user
        default_dev_output_filename = 'gpdb-' + args.pipeline_target + '-' + pipeline_file_suffix + '.yml'
        args.output_filepath = os.path.join(PIPELINES_DIR, default_dev_output_filename)

    pipeline_created = create_pipeline(args)

    if not pipeline_created:
        exit(1)

    print_fly_commands(args)
Beispiel #60
0
Press 1 : To display current date and time
Press 2 : To create a file
Press 3 : To create a directory
Press 4 : To search on google
Press 5 : To logout your system
Press 6 : To shutdown your os
Press 7 : To check internet connection in your pc
Press 8 : To login whatsapp on browser
Press 9 : To check all connected IP in your network
Press 0 : To exit
'''

choice = 0
while choice != '0':
    print option
    os.system('echo "enter your choice ' + os.getlogin() +
              ' " | festival --tts')
    #get user choice
    choice = raw_input("Enter Your Choice " + os.getlogin() + " : ")
    if choice == '1':
        #get current date & time in list format
        date_time = time.ctime().split()[1:4]
        print "Date :", date_time[1] + date_time[0], "& Time :", date_time[2]
    elif choice == '2':
        #get file name
        file_name = raw_input("Enter the file name : ")
        #get file path
        file_path = raw_input(
            "Enter the destination where you want to create the file or just enter for create in current location : "
        )
        #create file with the path given by the user