当前位置: 首页>>代码示例>>Python>>正文


Python FilePath.open方法代码示例

本文整理汇总了Python中twisted.python.filepath.FilePath.open方法的典型用法代码示例。如果您正苦于以下问题:Python FilePath.open方法的具体用法?Python FilePath.open怎么用?Python FilePath.open使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.python.filepath.FilePath的用法示例。


在下文中一共展示了FilePath.open方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_rewriteCss

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import open [as 别名]
	def test_rewriteCss(self):
		"""
		Test that CSS processing works, and verify the header.
		"""
		clock = Clock()
		fc = FileCache(lambda: clock.seconds(), 1)
		temp = FilePath(self.mktemp() + '.css')
		with temp.open('wb') as f:
			f.write("p { color: red; }\n")

		# BetterFile(temp.path) would not work because the processing happens
		# in getChild.  So, create a BetterFile for the .css file's parent dir.
		bf = BetterFile(temp.parent().path, fileCache=fc, rewriteCss=True)
		d = self._requestPostpathAndRender(bf, [temp.basename()])

		headerRe = re.compile(r"/\* CSSResource processed ([0-9a-f]{32}?) \*/")
		def assertProcessedContent((request, child)):
			out = "".join(request.written)
			lines = out.split("\n")
			self.assertTrue(re.match(headerRe, lines[0]), lines[0])
			self.assertEqual("p { color: red; }", lines[1])
			self.assertEqual("", lines[2])
			self.assertEqual(3, len(lines))
		d.addCallback(assertProcessedContent)
		return d
开发者ID:ludios,项目名称:Webmagic,代码行数:27,代码来源:test_untwist.py

示例2: init_introducer_clients

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import open [as 别名]
    def init_introducer_clients(self):
        self.introducer_clients = []
        self.introducer_furls = []

        introducers_yaml_filename = os.path.join(self.basedir, "private", "introducers.yaml")
        introducers_filepath = FilePath(introducers_yaml_filename)

        try:
            with introducers_filepath.open() as f:
                introducers_yaml = yamlutil.safe_load(f)
                introducers = introducers_yaml.get("introducers", {})
                log.msg("found %d introducers in private/introducers.yaml" %
                        len(introducers))
        except EnvironmentError:
            introducers = {}

        if "default" in introducers.keys():
            raise ValueError("'default' introducer furl cannot be specified in introducers.yaml; please fix impossible configuration.")

        # read furl from tahoe.cfg
        tahoe_cfg_introducer_furl = self.get_config("client", "introducer.furl", None)
        if tahoe_cfg_introducer_furl:
            introducers[u'default'] = {'furl':tahoe_cfg_introducer_furl}

        for petname, introducer in introducers.items():
            introducer_cache_filepath = FilePath(os.path.join(self.basedir, "private", "introducer_{}_cache.yaml".format(petname)))
            ic = IntroducerClient(self.tub, introducer['furl'],
                                  self.nickname,
                                  str(allmydata.__full_version__),
                                  str(self.OLDEST_SUPPORTED_VERSION),
                                  self.get_app_versions(), self._sequencer, introducer_cache_filepath)
            self.introducer_clients.append(ic)
            self.introducer_furls.append(introducer['furl'])
            ic.setServiceParent(self)
开发者ID:david415,项目名称:tahoe-lafs,代码行数:36,代码来源:client.py

示例3: test_file_logging_rotation_5_files

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import open [as 别名]
    def test_file_logging_rotation_5_files(self):
        """
        Only 5 logfiles are kept.
        """
        logfile = FilePath(self.mktemp()).child('foo.log')
        logfile.parent().makedirs()
        # This file will become foo.log.1
        with logfile.open('w') as f:
            f.write(b'0')
            f.truncate(int(MiB(100).to_Byte().value))
        # These file extensions will be incremented
        for i in range(1, 5):
            sibling = logfile.sibling(logfile.basename() + u'.' + unicode(i))
            with sibling.open('w') as f:
                f.write(bytes(i))

        d = self.run_script(EliotScript, options=['--logfile', logfile.path])

        def verify_logfiles(stdout_messages, logfile):
            logfile_dir = logfile.parent()
            self.assertEqual(
                # The contents of the files will now be an integer one less
                # than the integer in the file name.
                map(bytes, range(0, 4)),
                list(
                    logfile_dir.child('foo.log.{}'.format(i)).open().read(1)
                    for i
                    in range(1, 5)
                )
            )
        d.addCallback(verify_logfiles, logfile=logfile)

        return d
开发者ID:gitstorage,项目名称:flocker,代码行数:35,代码来源:test_script.py

示例4: setUp

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import open [as 别名]
 def setUp(self):
     """
     Create a temporary file with a fixed payload of 64 bytes.  Create a
     resource for that file and create a request which will be for that
     resource.  Each test can set a different range header to test different
     aspects of the implementation.
     """
     path = FilePath(self.mktemp())
     # This is just a jumble of random stuff.  It's supposed to be a good
     # set of data for this test, particularly in order to avoid
     # accidentally seeing the right result by having a byte sequence
     # repeated at different locations or by having byte values which are
     # somehow correlated with their position in the string.
     self.payload = ('\xf8u\xf3E\x8c7\xce\x00\x9e\xb6a0y0S\xf0\xef\xac\xb7'
                     '\xbe\xb5\x17M\x1e\x136k{\x1e\xbe\x0c\x07\x07\t\xd0'
                     '\xbckY\xf5I\x0b\xb8\x88oZ\x1d\x85b\x1a\xcdk\xf2\x1d'
                     '&\xfd%\xdd\x82q/A\x10Y\x8b')
     path.setContent(self.payload)
     self.file = path.open()
     self.resource = static.File(self.file.name)
     self.resource.isLeaf = 1
     self.request = DummyRequest([''])
     self.request.uri = self.file.name
     self.catcher = []
     log.addObserver(self.catcher.append)
开发者ID:AnthonyNystrom,项目名称:YoGoMee,代码行数:27,代码来源:test_static.py

示例5: main

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import open [as 别名]
def main(reactor):
    print "Message size: %d bytes   Num messages: %d" % (LENGTH, MESSAGES)
    message = b"a" * LENGTH
    fp = FilePath(tempfile.mktemp())
    writer = ThreadedFileWriter(fp.open("ab"), reactor)
    writer.startService()

    start = time.time()
    for i in range(MESSAGES):
        writer(message)
    d = writer.stopService()

    def done(_):
        elapsed = time.time() - start
        kbSec = (LENGTH * MESSAGES) / (elapsed * 1024)
        messagesSec = MESSAGES / elapsed
        print "messages/sec: %s   KB/sec: %s" % (messagesSec, kbSec)
    d.addCallback(done)

    def cleanup(result):
        fp.restat()
        print
        print "File size: ", fp.getsize()
        fp.remove()
    d.addBoth(cleanup)
    return d
开发者ID:adamtheturtle,项目名称:eliot,代码行数:28,代码来源:logwriter.py

示例6: activate

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import open [as 别名]
 def activate(self):
     super(StarboundConfigManager, self).activate()
     try:
         configuration_file = FilePath(
             self.config.starbound_path
         ).child('starbound.config')
         if not configuration_file.exists():
             raise FatalPluginError(
                 'Could not open starbound configuration file. '
                 'Tried path: {}'.format(configuration_file)
             )
     except AttributeError:
         raise FatalPluginError(
             'The starbound path (starbound_path)'
             ' is not set in the configuration.'
         )
     try:
         with configuration_file.open() as f:
             starbound_config = json.load(f)
     except Exception as e:
         raise FatalPluginError(
             'Could not parse the starbound configuration file as JSON.'
             'Error given from JSON decoder: {}'.format(e)
         )
     if self.config.upstream_port != starbound_config['gameServerPort']:
         raise FatalPluginError(
             'The starbound gameServerPort option ({}) does not match the '
             'config.json upstream_port ({}).'.format(
                 starbound_config['gameServerPort'],
                 self.config.upstream_port
             )
         )
开发者ID:GermaniumSystem,项目名称:StarryPy,代码行数:34,代码来源:starbound_config_manager.py

示例7: create_zfs_pool

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import open [as 别名]
def create_zfs_pool(test_case):
    """Create a new ZFS pool, then delete it after the test is over.

    :param test_case: A ``unittest.TestCase``.

    :return: The pool's name as ``bytes``.
    """
    if os.getuid() != 0:
        raise SkipTest("Functional tests must run as root.")

    pool_name = b"testpool_%s" % (uuid.uuid4(),)
    pool_path = FilePath(test_case.mktemp())
    mount_path = FilePath(test_case.mktemp())
    with pool_path.open("wb") as f:
        f.truncate(100 * 1024 * 1024)
    test_case.addCleanup(pool_path.remove)
    try:
        run_process([b"zpool", b"create", b"-m", mount_path.path,
                     pool_name, pool_path.path])
    except OSError as e:
        if e.errno == errno.ENOENT:
            raise SkipTest(
                "Install zpool to run these tests: "
                "http://doc-dev.clusterhq.com/using/installing/index.html"
                "#optional-zfs-backend-configuration")

        raise
    test_case.addCleanup(run_process, [b"zpool", b"destroy", pool_name])
    return pool_name
开发者ID:ClusterHQ,项目名称:flocker,代码行数:31,代码来源:testtools.py

示例8: render_POST

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import open [as 别名]
 def render_POST(self, request):
     
     context = self._context(request)
     
     form, status, appstruct = self._validate_form(request)
     
     if status == 'ok':
         filename = context['renderer'](appstruct)
         
         fileobj = FilePath(filename)
         
         request.setHeader('content-disposition', 'attachment; filename="output.pdf"')
         request.setHeader('content-length', str(fileobj.getsize()))
         request.setHeader('content-type', 'application/pdf')
         
         producer = NoRangeStaticProducer(request, fileobj.open('r'))
         
         producer.start()
         
         return NOT_DONE_YET
     
     data['renderer_form'] = form.render(appstruct)
     
     self.render_template(data, request)
     
     return NOT_DONE_YET
开发者ID:jjmojojjmojo,项目名称:jira-autoprint,代码行数:28,代码来源:__init__.py

示例9: get_client

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import open [as 别名]
def get_client(options):
    cluster = FilePath(options["cluster-yml"])
    if cluster.exists():
        config = yaml.load(cluster.open())
        certificates_path = cluster.parent()
        user = config["users"][0]
        control_service = None # figure it out based on cluster.yml
    else:
        certificates_path = FilePath(options["certs-path"])
        if options["user"] is None:
            raise UsageError("must specify --user")
        user = options["user"]
        if options["control-service"] is None:
            raise UsageError("must specify --control-service")
        control_service = options["control-service"]

    user_certificate_filename = "%s.crt" % (user,)
    user_key_filename = "%s.key" % (user,)

    return txflocker_get_client(
        certificates_path=certificates_path,
        user_certificate_filename=user_certificate_filename,
        user_key_filename=user_key_filename,
        target_hostname=control_service,
    )
开发者ID:sandlbn,项目名称:unofficial-flocker-tools,代码行数:27,代码来源:flocker_volumes.py

示例10: handle_config

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import open [as 别名]
def handle_config():
    if request.method == 'POST':    
        log.msg('Received JSON post with config')     
        jsonConfig = request.get_json(True)
        mumudvbConfig = ConfigParser.SafeConfigParser()
        for cardConfig in jsonConfig:
            card = cardConfig['_']['card']
            # Check the type, dvb-c = freq/1,000, dvb-s(2) = freq/1,000,000
            type = cardConfig['_']['type'] 
            if (type == 'DVB-C'):
                cardConfig['_']['freq'] =  int(cardConfig['_']['freq'])/1000
            else:
                cardConfig['_']['freq'] =  int(cardConfig['_']['freq'])/1000000
            # The DVB-S2 type needs an additional delivery system option
            if (type == 'DVB-S2'):
                cardConfig['_']['delivery_system'] = type
            cardConfig['_']['srate'] = int(cardConfig['_']['srate'])/1000
            cardConfig['_']['log_file'] = '/var/log/mumudvb' + card
            cardConfig['_']['log_type'] = 'syslog' 
            for section in sorted(cardConfig, reverse=True):                
                mumudvbConfig.add_section(section)
                for key in cardConfig[section]:
                    if (cardConfig[section][key] != None and key != 'type'):
                            mumudvbConfig.set(section,str(key),str(cardConfig[section][key]))                            
            cardConf = FilePath(tmpdir.path+'/dvbrc_adapter' + card + '.conf')
            with FilePath.open(cardConf, 'wb') as configfile:   
                mumudvbConfig.write(configfile)
            if FilePath.isfile(cardConf):
                mumu = startMumudvb(card)
                cmd = ["mumudvb","-d","-c", cardConf.path]
                log.msg('Starting MuMuDVB with the following flags: ' + str(cmd) + ' on card ' + card)
                process = reactor.spawnProcess(mumu, cmd[0], cmd, usePTY=True, env=None)
                log.msg(process)
    return ''
开发者ID:tijmenNL,项目名称:ip_streamer_v2,代码行数:36,代码来源:main.py

示例11: main

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import open [as 别名]
def main(wpImportFile, nikolaRoot):
    wpImportFile = FilePath(wpImportFile)
    nikolaRoot = FilePath(nikolaRoot)

    wpImport = parse(wpImportFile.open())
    for post in wpImport.iterfind('/channel/item'):
        if post.findtext('{http://wordpress.org/export/1.2/}status') != u'publish':
            continue
        updateDisqusId(disqusId(post), metaFile(nikolaRoot, post))
开发者ID:mithrandi,项目名称:mithrandi.net,代码行数:11,代码来源:fix_disqus.py

示例12: test_json_file_userdata

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import open [as 别名]
 def test_json_file_userdata(self):
     """
     JSON file adds to result.
     """
     json_file = FilePath(self.mktemp())
     with json_file.open('w') as f:
         f.write('{"branch": "master"}\n')
     options = BenchmarkOptions()
     options.parseOptions(['--userdata', '@{}'.format(json_file.path)])
     self.assertEqual(parse_userdata(options), {"branch": "master"})
开发者ID:332054781,项目名称:flocker,代码行数:12,代码来源:test_script.py

示例13: RemoteOriginReadOptionNegotiation

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import open [as 别名]
class RemoteOriginReadOptionNegotiation(unittest.TestCase):
    test_data = """line1
line2
anotherline"""
    port = 65466

    def setUp(self):
        self.clock = Clock()
        self.tmp_dir_path = tempfile.mkdtemp()
        self.target = FilePath(self.tmp_dir_path).child('foo')
        with self.target.open('wb') as temp_fd:
            temp_fd.write(self.test_data)
        self.reader = DelayedReader(self.target, _clock=self.clock, delay=2)
        self.transport = FakeTransport(hostAddress=('127.0.0.1', self.port))
        self.rs = RemoteOriginReadSession(('127.0.0.1', 65465), self.reader,
                                          options={'blksize':'9'}, _clock=self.clock)
        self.rs.transport = self.transport

    def test_option_normal(self):
        self.rs.startProtocol()
        self.clock.advance(0.1)
        oack_datagram = OACKDatagram({'blksize':'9'}).to_wire()
        self.assertEqual(self.transport.value(), oack_datagram)
        self.clock.advance(3)
        self.assertEqual(self.transport.value(), oack_datagram * 2)

        self.transport.clear()
        self.rs.datagramReceived(ACKDatagram(0).to_wire(), ('127.0.0.1', 65465))
        self.clock.pump((1,)*3)
        self.assertEqual(self.transport.value(), DATADatagram(1, self.test_data[:9]).to_wire())

        self.addCleanup(self.rs.cancel)

    def test_option_timeout(self):
        self.rs.startProtocol()
        self.clock.advance(0.1)
        oack_datagram = OACKDatagram({'blksize':'9'}).to_wire()
        self.assertEqual(self.transport.value(), oack_datagram)
        self.failIf(self.transport.disconnecting)

        self.clock.advance(3)
        self.assertEqual(self.transport.value(), oack_datagram * 2)
        self.failIf(self.transport.disconnecting)

        self.clock.advance(2)
        self.assertEqual(self.transport.value(), oack_datagram * 3)
        self.failIf(self.transport.disconnecting)

        self.clock.advance(2)
        self.assertEqual(self.transport.value(), oack_datagram * 3)
        self.failUnless(self.transport.disconnecting)

    def tearDown(self):
        shutil.rmtree(self.tmp_dir_path)
开发者ID:rvbad,项目名称:python-tx-tftp,代码行数:56,代码来源:test_bootstrap.py

示例14: deviceList

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import open [as 别名]
 def deviceList(self, request, tag):
     if not CommandServer.isDisabled:
         for device in sorted(self.deviceServerFactory.devices):
             try:
                 device_path = FilePath('hamjab/resources/devices/{device}/device.json'.format(device=device))
                 with device_path.open() as device_file:
                     device_data = json.load(device_file)
                     deviceName = device_data['name'] 
             except Exception:
                 deviceName = device
             yield tag.clone().fillSlots(deviceId = device, deviceName = deviceName)
开发者ID:midgetspy,项目名称:hamjab,代码行数:13,代码来源:web.py

示例15: initialize_testlocal_state

# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import open [as 别名]
 def initialize_testlocal_state(self, test_name):
     timestamp = '1970-01-01T00:00:00Z'
     fpcleantimestamp = timestamp.replace(':', '')
     logdirname = "%s-%s" % (fpcleantimestamp, self.MENCODED_IDS)
     testconfigdir = self.mockconfigdir.child(test_name).child('secrets').child(self.MPLAN_ID).child(logdirname)
     testconfigdir.makedirs()
     MLOGFILE_fp = FilePath(testconfigdir.path + '/signup_logs')
     MSSEC2_secretsfile = FilePath(testconfigdir.path + '/SSEC2').open('a+')
     signup_logfile = MLOGFILE_fp.open('a+')
     signup_stdout = LoggingStream(signup_logfile, '>')
     signup_stderr = LoggingStream(signup_logfile, '')
     return signup_stdout, signup_stderr, MLOGFILE_fp.path, MSSEC2_secretsfile
开发者ID:BenKoerber,项目名称:leastauthority.com,代码行数:14,代码来源:test_signup.py


注:本文中的twisted.python.filepath.FilePath.open方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。