本文整理汇总了Python中executor.execute函数的典型用法代码示例。如果您正苦于以下问题:Python execute函数的具体用法?Python execute怎么用?Python execute使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了execute函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: apt_supports_trusted_option
def apt_supports_trusted_option():
"""
Since apt version 0.8.16~exp3 the option ``[trusted=yes]`` can be used in a
``sources.list`` file to disable GPG key checking (see `Debian bug
#596498`_). This version of apt is included with Ubuntu 12.04 and later,
but deb-pkg-tools also has to support older versions of apt. The
:py:func:`apt_supports_trusted_option()` function checks if the installed
version of apt supports the ``[trusted=yes]`` option, so that deb-pkg-tools
can use it when possible.
:returns: ``True`` if the option is supported, ``False`` if it is not.
.. _Debian bug #596498: http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=596498
"""
global trusted_option_supported
if trusted_option_supported is None:
try:
# Find the installed version of the `apt' package.
version = execute('dpkg-query','--show', '--showformat=${Version}', 'apt', capture=True)
# Check if the version is >= 0.8.16 (which includes [trusted=yes] support).
execute('dpkg','--compare-versions', version, 'ge', '0.8.16~exp3')
# If ExternalCommandFailed is not raised,
# `dpkg --compare-versions' reported succes.
trusted_option_supported = True
except ExternalCommandFailed:
trusted_option_supported = False
return trusted_option_supported
示例2: runInteractive
def runInteractive():
"""
Main function for interactive mode
"""
print "------------- Welcome to the Miner %s ----------------" % miner_version.version
print "You can run HELP command anytime to get more information."
print "Press TAB key for context base completion"
print " - F1 key to get context base HELP"
print " - Ctrl-H to get list of keyboard bindings"
print " - Ctrl-D to exit"
while True:
s = ""
try:
s = raw_input(">>> ")
except KeyboardInterrupt:
print
continue
except EOFError:
break
if not s: continue
executor.execute(s)
if statements.Import.checkIfWasModified():
global theSymbolCompleter
theSymbolCompleter = CompleterWrap()
print "\nGoodbye"
示例3: runInteractive
def runInteractive():
"""
Main function for interactive mode
"""
print "------------- Welcome to the Miner %s ----------------" % miner_version.version
print "You can run HELP command anytime to get more information."
print "Press TAB key for context base completion"
print " - F1 key to get miner command help"
print " - F2 key to get python documentation"
print " - Ctrl-K to get list of keyboard bindings"
print " - Ctrl-D to exit"
miner_globals.setIsInteractive(True)
while True:
s = ""
try:
s = raw_input(">>> ")
except KeyboardInterrupt:
print
continue
except EOFError:
break
if not s: continue
executor.execute(s)
print "\nGoodbye"
示例4: wkhtml_to_pdf
def wkhtml_to_pdf(cls, data, options=None):
"""
Call wkhtmltopdf to convert the html to pdf
"""
with tempfile.NamedTemporaryFile(
suffix='.html', prefix='trytond_', delete=False
) as source_file:
file_name = source_file.name
source_file.write(data)
source_file.close()
# Evaluate argument to run with subprocess
args = 'wkhtmltopdf'
# Add Global Options
if options:
for option, value in options.items():
args += ' --%s' % option
if value:
args += ' "%s"' % value
# Add source file name and output file name
args += ' %s %s.pdf' % (file_name, file_name)
# Execute the command using executor
execute(args)
return open(file_name + '.pdf').read()
示例5: test_subprocess_output
def test_subprocess_output(self):
self.assertEqual(execute('echo', 'this is a test', capture=True), 'this is a test')
self.assertEqual(execute('echo', '-e', r'line 1\nline 2', capture=True), 'line 1\nline 2\n')
# I don't know how to test for the effect of silent=True in a practical
# way without creating the largest test in this test suite :-). The
# least I can do is make sure the keyword argument is accepted and the
# code runs without exceptions in supported environments.
self.assertTrue(execute('echo', 'this is a test', silent=True))
示例6: copy_package_files
def copy_package_files(from_directory, to_directory, hard_links=True):
"""
Copy package files to a temporary directory, using hard links when possible.
:param from_directory: The pathname of a directory tree suitable for
packaging with ``dpkg-deb --build``.
:param to_directory: The pathname of a temporary build directory.
:param hard_links: Use hard links to speed up copying when possible.
This function copies a directory tree suitable for packaging with
``dpkg-deb --build`` to a temporary build directory so that individual
files can be replaced without changing the original directory tree. If the
build directory is on the same file system as the source directory, hard
links are used to speed up the copy. This function is used by
:func:`build_package()`.
"""
logger.info("Copying files (%s) to temporary directory (%s) ..",
format_path(from_directory), format_path(to_directory))
command = ['cp', '-a']
makedirs(to_directory)
if hard_links and ALLOW_HARD_LINKS:
# Check whether we can use hard links to speed up the copy. In the past
# this used the following simple and obvious check:
#
# os.stat(source_directory).st_dev == os.stat(build_directory).st_dev
#
# However this expression holds true inside schroot, yet `cp -al' fails
# when trying to create the hard links! This is why the following code now
# tries to create an actual hard link to verify that `cp -al' can be used.
test_file_from = None
test_file_to = None
try:
# Find a unique filename that we can create and destroy without
# touching any of the caller's files.
while True:
test_name = 'deb-pkg-tools-hard-link-test-%d' % random.randint(1, 1000)
test_file_from = os.path.join(from_directory, test_name)
test_file_to = os.path.join(to_directory, test_name)
if not os.path.isfile(test_file_from):
break
# Create the test file.
with open(test_file_from, 'w') as handle:
handle.write('test')
os.link(test_file_from, test_file_to)
logger.debug("Speeding up file copy using hard links ..")
command.append('-l')
except (IOError, OSError):
pass
finally:
for test_file in [test_file_from, test_file_to]:
if test_file and os.path.isfile(test_file):
os.unlink(test_file)
# I know this looks really funky, but this is a valid use of shell escaping
# and globbing (obviously I tested it ;-).
command.append('%s/*' % pipes.quote(from_directory))
command.append(pipes.quote(to_directory))
execute(' '.join(command), logger=logger)
示例7: execute
def execute(stockId=None, date=None):
now = datetime.datetime.now()
if date is None or len(date)==0:
#convert western calendar to R.O.C calendar
date = str(now.year-1911) + "{:02d}".format(now.month) + "{:02d}".format(now.day)
elif len(date)==4:
date = str(now.year-1911) + date[0:2] + date[2:4]
executor.execute(stockId, date)
示例8: rotate_backups
def rotate_backups(self, directory):
"""
Rotate the backups in a directory according to a flexible rotation scheme.
:param directory: The pathname of a directory that contains backups to
rotate (a string).
.. note:: This function binds the main methods of the
:class:`RotateBackups` class together to implement backup
rotation with an easy to use Python API. If you're using
`rotate-backups` as a Python API and the default behavior is
not satisfactory, consider writing your own
:func:`rotate_backups()` function based on the underlying
:func:`collect_backups()`, :func:`group_backups()`,
:func:`apply_rotation_scheme()` and
:func:`find_preservation_criteria()` methods.
"""
# Load configuration overrides by user?
# Collect the backups in the given directory. if rotate type is on local or on google drive
sorted_backups = self.collect_backups(directory, self.rotate_type)
if not sorted_backups:
logger.info("No backups found in %s.", self.custom_format_path(directory))
return
most_recent_backup = sorted_backups[-1]
# Group the backups by the rotation frequencies.
backups_by_frequency = self.group_backups(sorted_backups)
# Apply the user defined rotation scheme.
self.apply_rotation_scheme(backups_by_frequency, most_recent_backup.datetime)
# Find which backups to preserve and why.
backups_to_preserve = self.find_preservation_criteria(backups_by_frequency)
# Apply the calculated rotation scheme.
for backup in sorted_backups:
if backup in backups_to_preserve:
matching_periods = backups_to_preserve[backup]
logger.info("Preserving %s (matches %s retention %s) ..",
self.custom_format_path(backup.pathname),
concatenate(map(repr, matching_periods)),
"period" if len(matching_periods) == 1 else "periods")
else:
logger.info("Deleting %s %s ..", backup.type, self.custom_format_path(backup.pathname))
if not self.dry_run:
timer = Timer()
if self.rotate_type == 'local': # if rotate type is on local or on google drive
command = ['rm', '-Rf', backup.pathname]
if self.io_scheduling_class:
command = ['ionice', '--class', self.io_scheduling_class] + command
execute(*command, logger=logger)
else:
self.gdrivecm.delete_file(backup.pathname.split('_')[0])
logger.debug("Deleted %s in %s.", self.custom_format_path(backup.pathname), timer)
if len(backups_to_preserve) == len(sorted_backups):
logger.info("Nothing to do! (all backups preserved)")
示例9: generate_key_file
def generate_key_file(self, filename):
"""
Generate a temporary host or client key for the OpenSSH server.
The :func:`start()` method automatically calls :func:`generate_key_file()`
to generate :data:`host_key_file` and :attr:`client_key_file`. This
method uses the ``ssh-keygen`` program to generate the keys.
"""
if not os.path.isfile(filename):
timer = Timer()
self.logger.debug("Generating SSH key file (%s) ..", filename)
execute('ssh-keygen', '-f', filename, '-N', '', '-t', 'rsa', silent=True, logger=self.logger)
self.logger.debug("Generated key file %s in %s.", filename, timer)
示例10: test_status_code_checking
def test_status_code_checking(self):
self.assertTrue(execute('true'))
self.assertFalse(execute('false', check=False))
self.assertRaises(ExternalCommandFailed, execute, 'false')
try:
execute('bash', '-c', 'exit 42')
# Make sure the previous line raised an exception.
self.assertTrue(False)
except Exception as e:
# Make sure the expected type of exception was raised.
self.assertTrue(isinstance(e, ExternalCommandFailed))
# Make sure the exception has the expected properties.
self.assertEqual(e.command, "bash -c 'exit 42'")
self.assertEqual(e.returncode, 42)
示例11: run
def run(args):
if (len(args) == 0) or (len(args) % 2 == 1):
print(messages.HELP_STRING)
return
iterator = iter(args)
jobs = izip(iterator, iterator)
for job_path, params_json in jobs:
try:
job = simplejson.loads(file_get_contents(job_path))
validictory.validate(job, job_schema)
params = simplejson.loads(params_json)
execute(job, params)
except Exception, error:
print(error)
示例12: application
def application(request):
"""
To use this application, the user must send a POST request with
base64 or form encoded encoded HTML content and the wkhtmltopdf Options in
request data, with keys 'base64_html' and 'options'.
The application will return a response with the PDF file.
"""
if request.method != 'POST':
return
request_is_json = request.content_type.endswith('json')
with tempfile.NamedTemporaryFile(suffix='.html') as source_file:
if request_is_json:
# If a JSON payload is there, all data is in the payload
payload = json.loads(request.data)
source_file.write(payload['contents'].decode('base64'))
options = payload.get('options', {})
elif request.files:
# First check if any files were uploaded
source_file.write(request.files['file'].read())
# Load any options that may have been provided in options
options = json.loads(request.form.get('options', '{}'))
source_file.flush()
# Evaluate argument to run with subprocess
args = ['wkhtmltopdf']
# Add Global Options
if options:
for option, value in options.items():
args.append('--%s' % option)
if value:
args.append('"%s"' % value)
# Add source file name and output file name
file_name = source_file.name
args += [file_name, file_name + ".pdf"]
# Execute the command using executor
execute(' '.join(args))
return Response(
wrap_file(request.environ, open(file_name + '.pdf')),
mimetype='application/pdf',
)
示例13: mktx
def mktx(self, recip, amount):
if self.iscoinset():
command = self.coinbinary + " payto -f " + self.fee + " " + recip + " " + str(amount)
output = execute(command, capture="True")
return output
else:
return False
示例14: find_system_dependencies
def find_system_dependencies(self, shared_object_files):
"""
(Ab)use dpkg-shlibdeps_ to find dependencies on system libraries.
:param shared_object_files: The pathnames of the ``*.so`` file(s) contained
in the package (a list of strings).
:returns: A list of strings in the format of the entries on the
``Depends:`` line of a binary package control file.
.. _dpkg-shlibdeps: https://www.debian.org/doc/debian-policy/ch-sharedlibs.html#s-dpkg-shlibdeps
"""
logger.debug("Abusing `dpkg-shlibdeps' to find dependencies on shared libraries ..")
# Create a fake source package, because `dpkg-shlibdeps' expects this...
with TemporaryDirectory(prefix='py2deb-dpkg-shlibdeps-') as fake_source_directory:
# Create the debian/ directory expected in the source package directory.
os.mkdir(os.path.join(fake_source_directory, 'debian'))
# Create an empty debian/control file because `dpkg-shlibdeps' requires
# this (even though it is apparently fine for the file to be empty ;-).
open(os.path.join(fake_source_directory, 'debian', 'control'), 'w').close()
# Run `dpkg-shlibdeps' inside the fake source package directory, but
# let it analyze the *.so files from the actual build directory.
command = ['dpkg-shlibdeps', '-O', '--warnings=0'] + shared_object_files
output = execute(*command, directory=fake_source_directory, capture=True, logger=logger)
expected_prefix = 'shlibs:Depends='
if not output.startswith(expected_prefix):
msg = ("The output of dpkg-shlibdeps doesn't match the"
" expected format! (expected prefix: %r, output: %r)")
logger.warning(msg, expected_prefix, output)
return []
output = output[len(expected_prefix):]
dependencies = sorted(dependency.strip() for dependency in output.split(','))
logger.debug("Dependencies reported by dpkg-shlibdeps: %s", dependencies)
return dependencies
示例15: daemon
def daemon(self, control):
if self.iscoinset() and (control == "start" or control == "stop"):
command = self.coinbinary + " daemon " + control
output = execute(command, capture="True")
return True
else:
return False