本文整理汇总了Python中autopep8.fix_code方法的典型用法代码示例。如果您正苦于以下问题:Python autopep8.fix_code方法的具体用法?Python autopep8.fix_code怎么用?Python autopep8.fix_code使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类autopep8
的用法示例。
在下文中一共展示了autopep8.fix_code方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: prg2py_after_preproc
# 需要导入模块: import autopep8 [as 别名]
# 或者: from autopep8 import fix_code [as 别名]
def prg2py_after_preproc(data, parser_start, input_filename):
input_stream = antlr4.InputStream(data)
lexer = VisualFoxpro9Lexer(input_stream)
stream = antlr4.CommonTokenStream(lexer)
parser = VisualFoxpro9Parser(stream)
tree = run_parser(stream, parser, parser_start)
TreeCleanVisitor().visit(tree)
output_tree = PythonConvertVisitor(input_filename).visit(tree)
if not isinstance(output_tree, list):
return output_tree
output = add_indents(output_tree, 0)
options = autopep8.parse_args(['--max-line-length', '100000', '-'])
output = autopep8.fix_code(output, options)
tokens = list(tokenize.generate_tokens(io.StringIO(output).readline))
for i, token in enumerate(tokens):
token = list(token)
if token[0] == tokenize.STRING and token[1].startswith('u'):
token[1] = token[1][1:]
tokens[i] = tuple(token)
return tokenize.untokenize(tokens)
示例2: generate_pipeline
# 需要导入模块: import autopep8 [as 别名]
# 或者: from autopep8 import fix_code [as 别名]
def generate_pipeline(template, nb_graph, step_names, lightweight_components,
metadata):
"""Use the pipeline template to generate Python code."""
# All the Pipeline steps that do not have children
leaf_steps = graph_utils.get_leaf_nodes(nb_graph)
# create a dict with step names and their parameters
all_step_parameters = {step: sorted(nb_graph.nodes(data=True)[step]
.get('parameters', {}).keys())
for step in step_names}
pipeline_code = template.render(
nb_graph=nb_graph,
lightweight_components=lightweight_components,
step_names=step_names,
step_prevs=pipeline_dependencies_tasks(nb_graph),
leaf_steps=leaf_steps,
all_step_parameters=all_step_parameters,
**metadata
)
# fix code style using pep8 guidelines
return autopep8.fix_code(pipeline_code)
示例3: get_setup
# 需要导入模块: import autopep8 [as 别名]
# 或者: from autopep8 import fix_code [as 别名]
def get_setup(self):
# render template
with self.setup_path.open(encoding='utf-8') as f:
document = f.read()
template = Environment().from_string(document)
document = template.render(
package=self.package,
format_vcs=self._format_vcs,
)
# format by yapf
style = CreateGoogleStyle()
document, _changed = FormatCode(document, style_config=style)
# remove empty strings
while '\n\n' in document:
document = document.replace('\n\n', '\n')
# format by autopep8
document = fix_code(document)
return document
示例4: autopep8_fix_code_cell
# 需要导入模块: import autopep8 [as 别名]
# 或者: from autopep8 import fix_code [as 别名]
def autopep8_fix_code_cell(source, options=None, apply_config=None):
"""
Applies autopep8.fix_code and takes care of newline characters.
autopep8.fix_code automatically adds a final newline at the end,
e.g. ``autopep8.fix_code('a=1')`` yields 'a = 1\\n'.
Note that this is not related to the 'W292' flag, i.e.
``autopep8.fix_code('a=1', options=dict(ignore=('W292',)))`` gives
the same result.
For notebook code cells, this behaviour does not make sense, hence
newline is removed if ``source`` does not end with one.
"""
source_corrected = autopep8.fix_code(source,
apply_config=apply_config,
options=options)
if not source.endswith('\n'):
return source_corrected[:-1]
return source_corrected
示例5: format_string
# 需要导入模块: import autopep8 [as 别名]
# 或者: from autopep8 import fix_code [as 别名]
def format_string(cls, old_contents):
"""Format file for use with task queue."""
config_options = cls.make_config_dictionary()
config_options = {}
new_contents = autopep8.fix_code(old_contents, options=config_options)
return old_contents, new_contents, 'utf-8'
示例6: format_code
# 需要导入模块: import autopep8 [as 别名]
# 或者: from autopep8 import fix_code [as 别名]
def format_code(self, code: str, notebook: bool, **options) -> str:
from autopep8 import fix_code
return fix_code(code, options=options)
示例7: _format_script
# 需要导入模块: import autopep8 [as 别名]
# 或者: from autopep8 import fix_code [as 别名]
def _format_script(script):
try:
import black
formatter = partial(
black.format_str, mode=black.FileMode(line_length=80)
)
except ImportError:
# use autopep8 for python3.5
import autopep8
formatter = partial(
autopep8.fix_code, options={"aggressive": 1}
)
return formatter(script)
示例8: generate_lightweight_component
# 需要导入模块: import autopep8 [as 别名]
# 或者: from autopep8 import fix_code [as 别名]
def generate_lightweight_component(template, step_name, step_data, nb_path,
metadata):
"""Use the function template to generate Python code."""
step_source_raw = step_data.get('source', [])
def _encode_source(s):
# Encode line by line a multiline string
return "\n".join([line.encode("unicode_escape").decode("utf-8")
for line in s.splitlines()])
# Since the code will be wrapped in triple quotes inside the template,
# we need to escape triple quotes as they will not be escaped by
# encode("unicode_escape").
step_source = [re.sub(r"'''", "\\'\\'\\'", _encode_source(s))
for s in step_source_raw]
step_marshal_in = step_data.get('ins', [])
step_marshal_out = step_data.get('outs', [])
step_parameters = get_args(step_data.get('parameters', {}))
fn_code = template.render(
step_name=step_name,
function_body=step_source,
in_variables=step_marshal_in,
out_variables=step_marshal_out,
parameters=step_parameters,
nb_path=nb_path,
# step_parameters overrides the parameters fields of metadata
**{**metadata, **step_parameters}
)
# fix code style using pep8 guidelines
return autopep8.fix_code(fn_code)
示例9: do_show
# 需要导入模块: import autopep8 [as 别名]
# 或者: from autopep8 import fix_code [as 别名]
def do_show(self, line):
"""Show me the code!
"""
code = autopep8.fix_code("".join(self._generate_workflow_code()))
if self.options.no_highlight:
print code
else:
print highlight(code, PythonLexer(), TerminalFormatter())
示例10: do_gen
# 需要导入模块: import autopep8 [as 别名]
# 或者: from autopep8 import fix_code [as 别名]
def do_gen(self, line):
if os.path.exists(self.file_name):
prompt = u"确定要生成代码?之前的代码文件 '{}' 将被覆盖(y/n)".format(
self.file_name).encode("utf-8")
if raw_input(prompt) != 'y':
return
with open(self.file_name, "w") as f:
f.write(autopep8.fix_code("".join(self._generate_workflow_code())))
示例11: load_python_code
# 需要导入模块: import autopep8 [as 别名]
# 或者: from autopep8 import fix_code [as 别名]
def load_python_code():
import autopep8
py_code = autopep8.fix_code("\n".join(AppState.algo.python()))
GuiState.code_editor.setPlainText(py_code.replace("\t", " "), "", "")
示例12: gen
# 需要导入模块: import autopep8 [as 别名]
# 或者: from autopep8 import fix_code [as 别名]
def gen(path,
method=None,
query_params=None,
data=None,
content_type=None):
# generates python code representing a call via django client.
# useful for use in testing
method = method.lower()
t = jinja2.Template(template)
if method == 'get':
r = t.render(path=path,
data=query_params,
lower_case_method=method,
content_type=content_type)
else:
if query_params:
query_params = _encode_query_params(query_params)
path += query_params
if is_str_typ(data):
data = "'%s'" % data
r = t.render(path=path,
data=data,
lower_case_method=method,
query_params=query_params,
content_type=content_type)
return autopep8.fix_code(
r, options=autopep8.parse_args(['--aggressive', ''])
)
示例13: fix_file
# 需要导入模块: import autopep8 [as 别名]
# 或者: from autopep8 import fix_code [as 别名]
def fix_file(file_name, line_ranges, options=None, in_place=False,
diff=False, verbose=0, cwd=None):
"""Calls fix_code on the source code from the passed in file over the given
line_ranges.
- If diff then this returns the udiff for the changes, otherwise
returns the fixed code.
- If in_place the changes are written to the file.
"""
import codecs
from os import getcwd
from pep8radius.diff import get_diff
from pep8radius.shell import from_dir
if cwd is None:
cwd = getcwd()
with from_dir(cwd):
try:
with codecs.open(file_name, 'r', encoding='utf-8') as f:
original = f.read()
except IOError:
# Most likely the file has been removed.
# Note: it would be nice if we could raise here, specifically
# for the case of passing in a diff when in the wrong directory.
return ''
fixed = fix_code(original, line_ranges, options, verbose=verbose)
if in_place:
with from_dir(cwd):
with codecs.open(file_name, 'w', encoding='utf-8') as f:
f.write(fixed)
return get_diff(original, fixed, file_name) if diff else fixed
示例14: fix_code
# 需要导入模块: import autopep8 [as 别名]
# 或者: from autopep8 import fix_code [as 别名]
def fix_code(source_code, line_ranges, options=None, verbose=0):
'''Apply autopep8 over the line_ranges, returns the corrected code.
Note: though this is not checked for line_ranges should not overlap.
Example
-------
>>> code = "def f( x ):\\n if True:\\n return 2*x"
>>> print(fix_code(code, [(1, 1), (3, 3)]))
def f(x):
if True:
return 2 * x
'''
if options is None:
from pep8radius.main import parse_args
options = parse_args()
if getattr(options, "yapf", False):
from yapf.yapflib.yapf_api import FormatCode
result = FormatCode(source_code, style_config=options.style, lines=line_ranges)
# yapf<0.3 returns diff as str, >=0.3 returns a tuple of (diff, changed)
return result[0] if isinstance(result, tuple) else result
line_ranges = reversed(line_ranges)
# Apply line fixes "up" the file (i.e. in reverse) so that
# fixes do not affect changes we're yet to make.
partial = source_code
for start, end in line_ranges:
partial = fix_line_range(partial, start, end, options)
_maybe_print('.', end='', max_=1, verbose=verbose)
_maybe_print('', max_=1, verbose=verbose)
fixed = partial
return fixed
示例15: fix_line_range
# 需要导入模块: import autopep8 [as 别名]
# 或者: from autopep8 import fix_code [as 别名]
def fix_line_range(source_code, start, end, options):
"""Apply autopep8 (and docformatter) between the lines start and end of
source."""
# TODO confirm behaviour outside range (indexing starts at 1)
start = max(start, 1)
options.line_range = [start, end]
from autopep8 import fix_code
fixed = fix_code(source_code, options)
try:
if options.docformatter:
from docformatter import format_code
fixed = format_code(
fixed,
summary_wrap_length=options.max_line_length - 1,
description_wrap_length=(options.max_line_length
- 2 * options.indent_size),
pre_summary_newline=options.pre_summary_newline,
post_description_blank=options.post_description_blank,
force_wrap=options.force_wrap,
line_range=[start, end])
except AttributeError: # e.g. using autopep8.parse_args, pragma: no cover
pass
return fixed