本文整理汇总了Python中sys.version_info.major方法的典型用法代码示例。如果您正苦于以下问题:Python version_info.major方法的具体用法?Python version_info.major怎么用?Python version_info.major使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类sys.version_info
的用法示例。
在下文中一共展示了version_info.major方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: xorme
# 需要导入模块: from sys import version_info [as 别名]
# 或者: from sys.version_info import major [as 别名]
def xorme(data):
from random import randint
xor = [hex(x) for x in range(20, 256)][randint(0, len([hex(x) for x in range(20, 256)]) - 1)]
shellcode = ""
if version_info.major >= 3:
for x in hexlify(data.encode('utf8')):
y = x ^ int(xor, 16)
shellcode += '0x%02x,' % y
else:
for x in bytearray(data.decode("hex")):
y = x ^ int(xor, 16)
shellcode += '0x%02x,' % y
padding = str(shellcode) + str(xor)
shellcode = "EB095E8036"
shellcode += str(xor).replace("0x", "")
shellcode += "7408"
shellcode += "46"
shellcode += "EBF8"
shellcode += "E8F2FFFFFF"
shellcode += padding.replace("0x", "").replace(",", "")
return shellcode
示例2: _verify_python_version
# 需要导入模块: from sys import version_info [as 别名]
# 或者: from sys.version_info import major [as 别名]
def _verify_python_version(self, key, cafile, capath, cahostverify):
python_version_cur = ".".join([str(version_info.major),
str(version_info.minor),
str(version_info.micro)])
python_version_min = "2.7.9"
if StrictVersion(python_version_cur) < StrictVersion(python_version_min):
if cafile or capath:
raise AnsibleError('Unable to read %s from vault:'
' Using Python %s, and vault lookup plugin requires at least %s'
' to use an SSL context (VAULT_CACERT or VAULT_CAPATH)'
% (key, python_version_cur, python_version_min))
elif cahostverify:
raise AnsibleError('Unable to read %s from vault:'
' Using Python %s, and vault lookup plugin requires at least %s'
' to verify Vault certificate. (set VAULT_CAHOSTVERIFY to \'%s\''
' to disable certificate verification.)'
% (key, python_version_cur, python_version_min, DISABLE_VAULT_CAHOSTVERIFY))
示例3: __init__
# 需要导入模块: from sys import version_info [as 别名]
# 或者: from sys.version_info import major [as 别名]
def __init__(self, headers=None):
"""SimpleRequests constructor."""
# Determine which version of Python we're running.
if version_info.major == 3:
# Import our Python 3 variant of SimpleRequests
from .SimpleRequestsPy3 import SimpleRequests
self.request = SimpleRequests(headers)
elif version_info.major == 2:
# Import our Python 2 variant of SimpleRequests
from .SimpleRequestsPy2 import SimpleRequests
self.request = SimpleRequests(headers)
else:
# Throw an error since we're running with an
# unsupported version of the Python interpreter.
error('Invalid version of Python detected!')
示例4: _filter
# 需要导入模块: from sys import version_info [as 别名]
# 或者: from sys.version_info import major [as 别名]
def _filter(self, result, results_filter=None, return_filtered=False):
""" Filter results returned from AWS IAM.
:param result: Dict or list of dicts from AWS IAM response.
:param results_filter: Dict of filters by filter type.
:param return_filtered: Boolean to determine whether the filtered result is returned in result tuple.
:return: Result or Tuple of filtered result count and either full or filtered result depending on filter type.
"""
# Set default good result:
rtn = (len(result), result)
for filter_name in FILTER_NAMES:
if results_filter and filter_name in results_filter and filter_name in result[0]:
if version_info.major < 3:
regex = r'{}'.format(results_filter[filter_name].encode('utf-8'))
else:
regex = r'{}'.format(results_filter[filter_name])
filtered_result = [r for r in result if re.search(regex, r[filter_name], re.IGNORECASE)]
if return_filtered:
# Return filtered count and filtered result.
rtn = (len(filtered_result), filtered_result)
else:
# If Boolean not set return filtered count and full result.
rtn = (len(filtered_result), result)
return rtn
示例5: delete_list_member
# 需要导入模块: from sys import version_info [as 别名]
# 或者: from sys.version_info import major [as 别名]
def delete_list_member(self, list_id=None, member_id=None):
"""Delete member from a list.
:param list_id: The id value of a list (integer).
:param member_id: The id of a member of a list (integer).
:return Result in json format.
"""
url = "{}{}".format(self.base_url, self._endpoints["list_member"].format(list_id, member_id))
res = self._req.execute_call_v2('delete', url, verify=self.bundle, headers=self._headers,
proxies=self._req.get_proxies())
try:
return res.json()
except ValueError:
# Default response likely not in json format just return content as is.
# Covert bypes to string fro python 3.
if version_info.major < 3:
return res.content
return res.content.decode('utf-8')
示例6: test_setup_xml
# 需要导入模块: from sys import version_info [as 别名]
# 或者: from sys.version_info import major [as 别名]
def test_setup_xml(self, mock, scan_type, file_path, sha256, sha1, md5, description, scan_action, expected_results):
sep_client = Sepclient(get_config())
result = sep_client.setup_scan_xml(scan_type, file_path, sha256, sha1, md5, description, scan_action)
if version_info.major == 3:
test_results_parsed = ET.fromstring(expected_results)
results_parsed = ET.fromstring(result)
else:
test_results_parsed = ET.fromstring(expected_results.encode('utf8', 'ignore'))
results_parsed = ET.fromstring(result.encode('utf8', 'ignore'))
assert test_results_parsed.tag == results_parsed.tag
test_items_file = test_results_parsed.findall('Activity/OS/Files/File')
result_items_file = results_parsed.findall('Activity/OS/Files/File')
for i in range(len(test_items_file)):
assert test_items_file[i].attrib["name"] == result_items_file[i].attrib["name"]
test_items_hash = test_results_parsed.findall('Activity/OS/Files/File/Hash')
result_items_hash = results_parsed.findall('Activity/OS/Files/File/Hash')
for i in range(len(test_items_hash)):
assert test_items_hash[i].attrib["value"] == result_items_hash[i].attrib["value"]
示例7: xorme
# 需要导入模块: from sys import version_info [as 别名]
# 或者: from sys.version_info import major [as 别名]
def xorme(shellcode):
cache = shellcode
mylist = ["".join(x) for x in list(product("ABCDEF", repeat=2))]
insert = mylist[randint(0, len(mylist) - 1)]
xorfirst = [
r"\x40", # inc eax
r"\x43", # inc ebx
r"\x42", # inc edx
r"\x47", # inc edi
]
header = xorfirst[randint(0, len(xorfirst) - 1)]
header += r"\xEB\x0D"
header += xorfirst[randint(0, len(xorfirst) - 1)]
header += r"\x5E"
header += xorfirst[randint(0, len(xorfirst) - 1)]
header += r"\x80\x36"
header += r"\x" + insert
header += r"\x74\x0A\x46"
header += xorfirst[randint(0, len(xorfirst) - 1)]
header += r"\xEB\xF7"
header += xorfirst[randint(0, len(xorfirst) - 1)]
header += r"\xE8\xEF\xFF\xFF\xFF"
encode = ""
if version_info.major >= 3:
for x in hexlify(cache.encode('utf8')):
y = x ^ int("0x" + insert, 16)
test = r'\x%02x' % y
encode += test
else:
for x in bytearray(cache.decode("hex")):
y = x ^ int("0x" + insert, 16)
test = r'\x%02x' % y
encode += test
header += encode.upper()
header += r"\x" + insert
if r"\x00" in header.lower():
xorme(shellcode)
return header.lower().replace("\\x", "")
示例8: store
# 需要导入模块: from sys import version_info [as 别名]
# 或者: from sys.version_info import major [as 别名]
def store(self, space, labels, vsp_type):
"""Data to csv storage.
Stores a given (sub)vectorspace to the .csv format that STMT works
with. The space should be a dict where the key is a tuple with (int,
str), where int is the index number and str the document its topic
labels seperated by a whitespace. The value is your vector stored in
a list.
If you want to iteratively construct a space, provide a generator that
will feed batches of the space.
Parameters
----------
space : list
The vector space; a list with text.
labels : list
List with labels where each index corresponds to the text in space.
vps_type : string
Either train or test as appendix for the filename.
"""
csv_file = open("%s%s_%s.csv" % (self.dir, self.name, vsp_type), 'a')
csv_writer = writer(csv_file)
for i, zipped in enumerate(zip(labels, space)):
line = [str(i + 1), zipped[0], zipped[1]]
if version_info.major < 3: # fix py2 compat
line = [i.encode('utf8') for i in line]
csv_writer.writerow(line)
csv_file.close()
示例9: test_ensure_docker_available_or_raise
# 需要导入模块: from sys import version_info [as 别名]
# 或者: from sys.version_info import major [as 别名]
def test_ensure_docker_available_or_raise():
if version_info.major < 3:
not_found_error = OSError
else:
not_found_error = FileNotFoundError
with patch('subprocess.check_output', new=lambda x: raise_(not_found_error())):
with pytest.raises(MissingDependencyException) as error:
ensure_docker_available_or_raise()
assert str(error.value).startswith('Docker is required')
示例10: _cli_print_version
# 需要导入模块: from sys import version_info [as 别名]
# 或者: from sys.version_info import major [as 别名]
def _cli_print_version(ctx: Context, _: Any, value: Any) -> None: # pragma: no cover
if not value or ctx.resilient_parsing:
return
location = dirname(__file__)
echo(f'{__version} from {location} (python {version_info.major}.{version_info.minor})')
ctx.exit()
示例11: __init__
# 需要导入模块: from sys import version_info [as 别名]
# 或者: from sys.version_info import major [as 别名]
def __init__(self, keyword_sequence=None, search_method=DEFAULT_METHOD, conflict_resolving_strategy='MAX',
return_layer=False, layer_name='keywords'):
"""Initialize a new KeywordTagger instance.
Parameters
----------
keyword_sequence: list-like or dict-like
sequence of keywords to annotate
search_method: 'naive', 'ahocorasick'
Method to find events in text (default: 'naive' for python2 and 'ahocorasick' for python3).
conflict_resolving_strategy: 'ALL', 'MAX', 'MIN'
Strategy to choose between overlapping events (default: 'MAX').
return_layer: bool
if True, KeywordTagger.tag(text) returns a layer. If False, KeywordTagger.tag(text) annotates the text object with the layer instead.
layer_name: str
if return_layer is False, KeywordTagger.tag(text) annotates to this layer of the text object. Default 'keywords'
"""
if keyword_sequence is None:
raise ValueError("Can't really do something without keywords")
if hasattr(keyword_sequence, 'get'):
# I think we got a dict-like
self.keyword_sequence = list(keyword_sequence.keys())
self.mapping = True
self.map = keyword_sequence
else:
self.keyword_sequence = keyword_sequence
self.mapping = False
self.layer_name = layer_name
self.return_layer = return_layer
if search_method not in ['naive', 'ahocorasick']:
raise ValueError("Unknown search_method '%s'." % search_method)
if conflict_resolving_strategy not in ['ALL', 'MIN', 'MAX']:
raise ValueError("Unknown conflict_resolving_strategy '%s'." % conflict_resolving_strategy)
if search_method == 'ahocorasick' and version_info.major < 3:
raise ValueError(
"search_method='ahocorasick' is not supported by Python %s. Try 'naive' instead." % version_info.major)
self.search_method = search_method
self.ahocorasick_automaton = None
self.conflict_resolving_strategy = conflict_resolving_strategy
示例12: test_notebooks
# 需要导入模块: from sys import version_info [as 别名]
# 或者: from sys.version_info import major [as 别名]
def test_notebooks(tmpdir, filename):
""" Runs a given notebook in a tmpdir """
import pylada
from os.path import join, dirname
from nbformat import read
from nbconvert.preprocessors import ExecutePreprocessor
from sys import version_info
directory = dirname(__file__)
with open(join(directory, filename + ".ipynb")) as notebook_file:
notebook = read(notebook_file, as_version=4)
preprocessor = ExecutePreprocessor(kernel_name='python%i' %
version_info.major)
preprocessor.preprocess(notebook, {'metadata': {'path': str(tmpdir)}})
示例13: raise_value_error
# 需要导入模块: from sys import version_info [as 别名]
# 或者: from sys.version_info import major [as 别名]
def raise_value_error(v, k, msg=None):
if msg is None:
msg = "Invalid value"
if version_info.major == 2:
v = v.encode('utf-8')
raise ValueError("{2} '{0}' for function parameter '{1}'.".format(v, k, msg))
示例14: get_bf_action_status
# 需要导入模块: from sys import version_info [as 别名]
# 或者: from sys.version_info import major [as 别名]
def get_bf_action_status(self, action_id):
"""" Get Bigfix action status.
:param action_id: BigFix actions id
:return status: Return BigFix actions status
"""
query_url = u"{0}/api/action/{1}/status".format(self.base_url, action_id)
r = requests.get(query_url, auth=(self.bf_user, self.bf_pass), verify=False)
if r.status_code == 200:
try:
status = None
if version_info.major < 3:
xmlroot = elementTree.fromstring(r.text.encode('utf8'))
else:
xmlroot = elementTree.fromstring(r.text)
results = xmlroot.findall(".//ActionResults/Computer/Status")
if len(results) > 0:
status = results[0].text
LOG.debug("BigFix Action Status: %s BigFix Action ID: %s.", status, action_id)
except Exception as e:
LOG.exception("XML processing, Got exception type: %s, msg: %s", e.__repr__(), e.message)
raise e
else:
status = r.text
LOG.debug("Found an error trying to execution the action: %s. Action: %s", r.text, action_id)
return status
示例15: get_unzipped_contents
# 需要导入模块: from sys import version_info [as 别名]
# 或者: from sys.version_info import major [as 别名]
def get_unzipped_contents(content):
""" Unzip file content zip file returned in response.
Response zip will have contents as follows:
|- <file with hash (sha256) as name>
|- metadata.xml
:param content: Response content.
:return: Tuple with Unzipped file with hash as name and key.
"""
key = c_unzipped = meta = None
try:
with ZipFile(BytesIO(content), 'r') as zfile:
for zip_file_name in zfile.namelist():
if len(zip_file_name) in HASH_LENGTHS or zip_file_name == "metadata.xml":
f = zfile.open(zip_file_name)
if len(zip_file_name) in HASH_LENGTHS:
# Get the hash file name.
c_unzipped = f.read()
elif zip_file_name == "metadata.xml":
# Get the key.
if version_info.major == 3:
meta = ET.fromstring(f.read())
else:
meta = ET.fromstring(f.read().encode('utf8', 'ignore'))
for item in meta.findall('File'):
key = item.attrib["Key"]
else:
raise ValueError('Unknown hash type or key for zipfile contents: ' + zip_file_name)
return (key, c_unzipped)
except ET.ParseError as e:
LOG.error("During metadata file XML processing, Got exception type: %s, msg: %s", e.__repr__(), e.message)
raise e