本文整理汇总了Python中twisted.python.filepath.FilePath.remove方法的典型用法代码示例。如果您正苦于以下问题:Python FilePath.remove方法的具体用法?Python FilePath.remove怎么用?Python FilePath.remove使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twisted.python.filepath.FilePath
的用法示例。
在下文中一共展示了FilePath.remove方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: create_credentials
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import remove [as 别名]
def create_credentials():
"""
Create PKI credentials for TLS access to libvirtd.
Credentials are not signed by the host CA. This only allows
unverified access but removes the need to transfer files
between the host and the guest.
"""
path = FilePath(tempfile.mkdtemp())
try:
ca = RootCredential.initialize(path, b"mycluster")
NodeCredential.initialize(path, ca, uuid='client')
ca_dir = FilePath('/etc/pki/CA')
if not ca_dir.exists():
ca_dir.makedirs()
path.child(AUTHORITY_CERTIFICATE_FILENAME).copyTo(
FilePath('/etc/pki/CA/cacert.pem')
)
client_key_dir = FilePath('/etc/pki/libvirt/private')
if not client_key_dir.exists():
client_key_dir.makedirs()
client_key_dir.chmod(0700)
path.child('client.key').copyTo(
client_key_dir.child('clientkey.pem')
)
path.child('client.crt').copyTo(
FilePath('/etc/pki/libvirt/clientcert.pem')
)
finally:
path.remove()
示例2: test_unix_already_listening_cant_delete
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import remove [as 别名]
def test_unix_already_listening_cant_delete(self):
"""
A config with type = "unix" will create an endpoint for a UNIX socket
at the given path, and delete it if required. If it can't delete it, it
will raise an exception.
"""
parent_fp = FilePath("/tmp").child(uuid4().hex)
parent_fp.makedirs()
fp = parent_fp.child(uuid4().hex)
# Something is already there
fp.setContent(b"")
fp.chmod(0o544)
parent_fp.chmod(0o544)
reactor = SelectReactor()
config = {
"type": "unix",
"path": fp.path
}
with self.assertRaises(OSError) as e:
create_listening_endpoint_from_config(config, self.cbdir,
reactor, self.log)
self.assertEqual(e.exception.errno, 13) # Permission Denied
parent_fp.chmod(0o777)
parent_fp.remove()
示例3: TestFSStorageAssumptions
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import remove [as 别名]
class TestFSStorageAssumptions(unittest.TestCase):
def setUp(self):
self.tmp_content = FilePath(self.mktemp())
self.tmp_content.makedirs()
self.storage = fs_storage.FSStore(None, name='my media',
content=self.tmp_content.path,
urlbase='http://fsstore-host/xyz',
enable_inotify=False)
def tearDown(self):
self.tmp_content.remove()
pass
def test_ContentLen(self):
self.assertEqual(len(self.storage.content), 1)
self.assertEqual(len(self.storage.store), 1)
self.assertEqual(self.storage.len(), 1)
def test_Root(self):
root = self.storage.get_by_id('1000')
self.assertIs(root.parent, None)
self.assertRaises(AttributeError, getattr, root, 'path')
# A single path passed, so content is a "directory" named by
# it's basename
self.assertEqual(root.mimetype, 'directory')
self.assertEqual(root.get_name(), 'temp')
示例4: _UnixFixHome
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import remove [as 别名]
class _UnixFixHome(object):
"""
Mixin class to fix the HOME environment variable to something usable.
@ivar home: FilePath pointing at C{homePath}.
@type home: L{FilePath}
@ivar homePath: relative path to the directory used as HOME during the
tests.
@type homePath: C{str}
"""
def setUp(self):
path = self.mktemp()
self.home = FilePath(path)
self.homePath = os.path.join(*self.home.segmentsFrom(FilePath(".")))
if len(self.home.path) >= 70:
# UNIX_MAX_PATH is 108, and the socket file is generally of length
# 30, so we can't rely on mktemp...
self.homePath = "_tmp"
self.home = FilePath(self.homePath)
self.home.makedirs()
self.savedEnviron = os.environ.copy()
os.environ["HOME"] = self.homePath
def tearDown(self):
os.environ.clear()
os.environ.update(self.savedEnviron)
self.home.remove()
示例5: publish_artifacts_main
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import remove [as 别名]
def publish_artifacts_main(args, base_path, top_level):
"""
Publish release artifacts.
:param list args: The arguments passed to the scripts.
:param FilePath base_path: The executable being run.
:param FilePath top_level: The top-level of the flocker repository.
"""
options = UploadOptions()
try:
options.parseOptions(args)
except UsageError as e:
sys.stderr.write("%s: %s\n" % (base_path.basename(), e))
raise SystemExit(1)
except NotARelease:
sys.stderr.write("%s: Can't publish artifacts for a non-release.\n"
% (base_path.basename(),))
raise SystemExit(1)
except DocumentationRelease:
sys.stderr.write("%s: Can't publish artifacts for a documentation "
"release.\n" % (base_path.basename(),))
raise SystemExit(1)
dispatcher = ComposedDispatcher([boto_dispatcher, yum_dispatcher,
base_dispatcher])
scratch_directory = FilePath(tempfile.mkdtemp(
prefix=b'flocker-upload-'))
scratch_directory.child('packages').createDirectory()
scratch_directory.child('python').createDirectory()
scratch_directory.child('pip').createDirectory()
try:
sync_perform(
dispatcher=dispatcher,
effect=sequence([
upload_packages(
scratch_directory=scratch_directory.child('packages'),
target_bucket=options['target'],
version=options['flocker-version'],
build_server=options['build-server'],
top_level=top_level,
),
upload_python_packages(
scratch_directory=scratch_directory.child('python'),
target_bucket=options['target'],
top_level=top_level,
output=sys.stdout,
error=sys.stderr,
),
upload_pip_index(
scratch_directory=scratch_directory.child('pip'),
target_bucket=options['target'],
),
]),
)
finally:
scratch_directory.remove()
示例6: Writer
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import remove [as 别名]
class Writer(unittest.TestCase):
test_data = """line1
line2
line3
"""
def setUp(self):
self.temp_dir = FilePath(tempfile.mkdtemp())
self.existing_file_name = self.temp_dir.child("foo")
with self.existing_file_name.open("w") as f:
f.write(self.test_data)
def test_write_existing_file(self):
self.assertRaises(FileExists, FilesystemWriter, self.temp_dir.child("foo"))
def test_finished_write(self):
w = FilesystemWriter(self.temp_dir.child("bar"))
w.write(self.test_data)
w.finish()
with self.temp_dir.child("bar").open() as f:
self.assertEqual(f.read(), self.test_data)
def test_cancelled_write(self):
w = FilesystemWriter(self.temp_dir.child("bar"))
w.write(self.test_data)
w.cancel()
self.failIf(self.temp_dir.child("bar").exists(), "If a write is cancelled, the file should not be left behind")
def tearDown(self):
self.temp_dir.remove()
示例7: LocalOriginWriteOptionNegotiation
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import remove [as 别名]
class LocalOriginWriteOptionNegotiation(unittest.TestCase):
port = 65466
def setUp(self):
self.clock = Clock()
self.temp_dir = FilePath(tempfile.mkdtemp()).asBytesMode()
self.target = self.temp_dir.child(b'foo')
self.writer = DelayedWriter(self.target, _clock=self.clock, delay=2)
self.transport = FakeTransport(hostAddress=('127.0.0.1', self.port))
self.ws = LocalOriginWriteSession(('127.0.0.1', 65465), self.writer,
options={b'blksize':b'123'}, _clock=self.clock)
self.wd = MockHandshakeWatchdog(4, self.ws.timedOut, _clock=self.clock)
self.ws.timeout_watchdog = self.wd
self.ws.transport = self.transport
def test_option_normal(self):
self.ws.startProtocol()
self.ws.datagramReceived(OACKDatagram({b'blksize':b'12'}).to_wire(), ('127.0.0.1', 65465))
self.clock.advance(0.1)
self.assertEqual(self.ws.session.block_size, WriteSession.block_size)
self.assertEqual(self.transport.value(), ACKDatagram(0).to_wire())
self.transport.clear()
self.ws.datagramReceived(OACKDatagram({b'blksize':b'9'}).to_wire(), ('127.0.0.1', 65465))
self.clock.advance(0.1)
self.assertEqual(self.ws.session.block_size, WriteSession.block_size)
self.assertEqual(self.transport.value(), ACKDatagram(0).to_wire())
self.transport.clear()
self.ws.datagramReceived(DATADatagram(1, b'foobarbaz').to_wire(), ('127.0.0.1', 65465))
self.clock.advance(3)
self.assertTrue(self.ws.session.started)
self.clock.advance(0.1)
self.assertEqual(self.ws.session.block_size, 9)
self.assertEqual(self.transport.value(), ACKDatagram(1).to_wire())
self.transport.clear()
self.ws.datagramReceived(DATADatagram(2, b'asdfghjkl').to_wire(), ('127.0.0.1', 65465))
self.clock.advance(3)
self.assertEqual(self.transport.value(), ACKDatagram(2).to_wire())
self.writer.finish()
self.assertEqual(self.writer.file_path.open('r').read(), b'foobarbazasdfghjkl')
self.transport.clear()
self.ws.datagramReceived(OACKDatagram({b'blksize':b'12'}).to_wire(), ('127.0.0.1', 65465))
self.clock.advance(0.1)
self.assertEqual(self.ws.session.block_size, 9)
self.assertEqual(self.transport.value(), ACKDatagram(0).to_wire())
def test_option_timeout(self):
self.ws.startProtocol()
self.clock.advance(5)
self.assertTrue(self.transport.disconnecting)
def tearDown(self):
self.temp_dir.remove()
示例8: Reader
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import remove [as 别名]
class Reader(unittest.TestCase):
test_data = """line1
line2
line3
"""
def setUp(self):
self.temp_dir = FilePath(tempfile.mkdtemp())
self.existing_file_name = self.temp_dir.child('foo')
with self.existing_file_name.open('w') as f:
f.write(self.test_data)
def test_file_not_found(self):
self.assertRaises(FileNotFound, FilesystemReader, self.temp_dir.child('bar'))
def test_read_existing_file(self):
r = FilesystemReader(self.temp_dir.child('foo'))
data = r.read(3)
ostring = data
while data:
data = r.read(3)
ostring += data
self.assertEqual(r.read(3), '')
self.assertEqual(r.read(5), '')
self.assertEqual(r.read(7), '')
self.failUnless(r.file_obj.closed,
"The file has been exhausted and should be in the closed state")
self.assertEqual(ostring, self.test_data)
def test_size(self):
r = FilesystemReader(self.temp_dir.child('foo'))
self.assertEqual(len(self.test_data), r.size)
def test_size_when_reader_finished(self):
r = FilesystemReader(self.temp_dir.child('foo'))
r.finish()
self.assertIsNone(r.size)
def test_size_when_file_removed(self):
# FilesystemReader.size uses fstat() to discover the file's size, so
# the absence of the file does not matter.
r = FilesystemReader(self.temp_dir.child('foo'))
self.existing_file_name.remove()
self.assertEqual(len(self.test_data), r.size)
def test_cancel(self):
r = FilesystemReader(self.temp_dir.child('foo'))
r.read(3)
r.finish()
self.failUnless(r.file_obj.closed,
"The session has been finished, so the file object should be in the closed state")
r.finish()
def tearDown(self):
self.temp_dir.remove()
示例9: run
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import remove [as 别名]
def run(argv=None):
if argv is None:
argv = sys.argv
generated = FilePath(GENERATED_TILESETS)
if generated.exists():
generated.remove()
sets = discoverTilesets(FilePath('tiles'))
for ts in sets:
ts.writeResources()
示例10: test_0900_autoRepairKeyError
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import remove [as 别名]
def test_0900_autoRepairKeyError(self):
"""
"""
yield AsyncExecCmds(['/opt/HybridCluster/init.d/mysqld stop']).getDeferred()
sampleBadDataPath = FilePath(__file__).sibling('bad-data')
target = FilePath('/var/db/mysql/autorepair')
try:
target.remove()
except OSError, e:
if e.errno != ENOENT:
raise
示例11: buildPDF
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import remove [as 别名]
def buildPDF(self, bookPath, inputDirectory, outputPath):
"""
Build a PDF from the given a LaTeX book document.
@type bookPath: L{FilePath}
@param bookPath: The location of a LaTeX document defining a book.
@type inputDirectory: L{FilePath}
@param inputDirectory: The directory which the inputs of the book are
relative to.
@type outputPath: L{FilePath}
@param outputPath: The location to which to write the resulting book.
"""
if not bookPath.basename().endswith(".tex"):
raise ValueError("Book filename must end with .tex")
workPath = FilePath(mkdtemp())
try:
startDir = os.getcwd()
try:
os.chdir(inputDirectory.path)
texToDVI = (
"latex -interaction=nonstopmode "
"-output-directory=%s %s") % (
workPath.path, bookPath.path)
# What I tell you three times is true!
# The first two invocations of latex on the book file allows it
# correctly create page numbers for in-text references. Why this is
# the case, I could not tell you. -exarkun
for i in range(3):
self.run(texToDVI)
bookBaseWithoutExtension = bookPath.basename()[:-4]
dviPath = workPath.child(bookBaseWithoutExtension + ".dvi")
psPath = workPath.child(bookBaseWithoutExtension + ".ps")
pdfPath = workPath.child(bookBaseWithoutExtension + ".pdf")
self.run(
"dvips -o %(postscript)s -t letter -Ppdf %(dvi)s" % {
'postscript': psPath.path,
'dvi': dviPath.path})
self.run("ps2pdf13 %(postscript)s %(pdf)s" % {
'postscript': psPath.path,
'pdf': pdfPath.path})
pdfPath.moveTo(outputPath)
workPath.remove()
finally:
os.chdir(startDir)
except:
workPath.moveTo(bookPath.parent().child(workPath.basename()))
raise
示例12: validatePath
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import remove [as 别名]
def validatePath():
dbpath = FilePath(TimezoneCache.getDBPath())
if not dbpath.exists():
TimezoneCache.copyPackage("Copying")
else:
# Check if pkg is more recent and copy over
pkgversion = TimezoneCache.getTZVersion(TimezoneCache._getPackageDBPath())
dbversion = TimezoneCache.getTZVersion(dbpath.path)
if not dbversion or pkgversion > dbversion:
dbpath.remove()
TimezoneCache.copyPackage("Updating")
else:
log.info("Valid timezones at %s" % (dbpath.path,))
示例13: buildAllTarballs
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import remove [as 别名]
def buildAllTarballs(checkout, destination, templatePath=None):
"""
Build complete tarballs (including documentation) for Twisted and all
subprojects.
This should be called after the version numbers have been updated and
NEWS files created.
@type checkout: L{FilePath}
@param checkout: The SVN working copy from which a pristine source tree
will be exported.
@type destination: L{FilePath}
@param destination: The directory in which tarballs will be placed.
@type templatePath: L{FilePath}
@param templatePath: Location of the template file that is used for the
howto documentation.
@raise UncleanWorkingDirectory: If there are modifications to the
working directory of C{checkout}.
@raise NotWorkingDirectory: If the C{checkout} path is not an SVN checkout.
"""
if not checkout.child(".svn").exists():
raise NotWorkingDirectory(
"%s does not appear to be an SVN working directory."
% (checkout.path,))
if runCommand(["svn", "st", checkout.path]).strip():
raise UncleanWorkingDirectory(
"There are local modifications to the SVN checkout in %s."
% (checkout.path,))
workPath = FilePath(mkdtemp())
export = workPath.child("export")
runCommand(["svn", "export", checkout.path, export.path])
twistedPath = export.child("twisted")
version = Project(twistedPath).getVersion()
versionString = version.base()
apiBaseURL = "http://twistedmatrix.com/documents/%s/api/%%s.html" % (
versionString)
if not destination.exists():
destination.createDirectory()
db = DistributionBuilder(export, destination, templatePath=templatePath,
apiBaseURL=apiBaseURL)
db.buildCore(versionString)
for subproject in twisted_subprojects:
if twistedPath.child(subproject).exists():
db.buildSubProject(subproject, versionString)
db.buildTwisted(versionString)
workPath.remove()
示例14: buildAllTarballs
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import remove [as 别名]
def buildAllTarballs(checkout, destination, templatePath=None):
"""
Build complete tarballs (including documentation) for Twisted and all
subprojects.
This should be called after the version numbers have been updated and
NEWS files created.
@type checkout: L{FilePath}
@param checkout: The repository from which a pristine source tree will be
exported.
@type destination: L{FilePath}
@param destination: The directory in which tarballs will be placed.
@type templatePath: L{FilePath}
@param templatePath: Location of the template file that is used for the
howto documentation.
@raise UncleanWorkingDirectory: If there are modifications to the
working directory of C{checkout}.
@raise NotWorkingDirectory: If the C{checkout} path is not a supported VCS
repository.
"""
cmd = getRepositoryCommand(checkout)
cmd.ensureIsWorkingDirectory(checkout)
if not cmd.isStatusClean(checkout):
raise UncleanWorkingDirectory(
"There are local modifications to the repository in %s."
% (checkout.path,))
workPath = FilePath(mkdtemp())
export = workPath.child("export")
cmd.exportTo(checkout, export)
twistedPath = export.child("twisted")
version = Project(twistedPath).getVersion()
versionString = version.base()
if not destination.exists():
destination.createDirectory()
db = DistributionBuilder(export, destination, templatePath=templatePath)
db.buildCore(versionString)
for subproject in twisted_subprojects:
if twistedPath.child(subproject).exists():
db.buildSubProject(subproject, versionString)
db.buildTwisted(versionString)
workPath.remove()
示例15: publish_rpms_main
# 需要导入模块: from twisted.python.filepath import FilePath [as 别名]
# 或者: from twisted.python.filepath.FilePath import remove [as 别名]
def publish_rpms_main(args, base_path, top_level):
"""
The ClusterHQ yum repository contains packages for Flocker, as well as the
dependencies which aren't available in Fedora 20 or CentOS 7. It is
currently hosted on Amazon S3. When doing a release, we want to add the
new Flocker packages, while preserving the existing packages in the
repository. To do this, we download the current repository, add the new
package, update the metadata, and then upload the repository.
:param list args: The arguments passed to the script.
:param FilePath base_path: The executable being run.
:param FilePath top_level: The top-level of the flocker repository.
"""
options = UploadOptions()
try:
options.parseOptions(args)
except UsageError as e:
sys.stderr.write("%s: %s\n" % (base_path.basename(), e))
raise SystemExit(1)
dispatcher = ComposedDispatcher([boto_dispatcher, yum_dispatcher,
base_dispatcher])
try:
scratch_directory = FilePath(tempfile.mkdtemp(
prefix=b'flocker-upload-rpm-'))
sync_perform(
dispatcher=dispatcher,
effect=upload_rpms(
scratch_directory=scratch_directory,
target_bucket=options['target'],
version=options['flocker-version'],
build_server=options['build-server'],
))
except NotARelease:
sys.stderr.write("%s: Can't upload RPMs for a non-release."
% (base_path.basename(),))
raise SystemExit(1)
except DocumentationRelease:
sys.stderr.write("%s: Can't upload RPMs for a documentation release."
% (base_path.basename(),))
raise SystemExit(1)
finally:
scratch_directory.remove()