向现有代码添加循环语句时的 Python 缩进

发布于 2024-09-27 13:41:57 字数 178 浏览 3 评论 0原文

在Python中,当你写了100行代码却忘记在某处添加一堆循环语句时,你会怎么做?

我的意思是,如果您在某处添加 while 语句,您现在必须缩进其下面的所有行。这并不是说你只要戴上牙套就可以完成它。转到每一行并添加制表符/空格。如果您向现有代码添加嵌套循环/if/then 语句会怎样?

我错过了一些捷径吗?

In Python, what do you do when you write 100 lines of code and forget to add a bunch of loop statements somewhere?

I mean, if you add a while statement somewhere, you've to now indent all the lines below it. It's not like you can just put braces and be done with it. Go to every single line and add tabs/spaces. What if you were adding nested loops/if/then statements to existing code?

Am I missing some shortcut?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

御守 2024-10-04 13:41:57

我认为每个严肃的编辑器或 IDE 都支持选择多行并按 Tab 缩进或 Shift-Tab 取消所有行缩进的选项。

I think every serious editor or IDE supports the option to select multiple lines and press tab to indent or Shift-Tab to unindent all that lines.

乖乖兔^ω^ 2024-10-04 13:41:57

在IDLE(标准Python IDE)中,选择代码,继续“格式”,您可以选择缩进区域、缩进区域等

in IDLE, the standard python IDE, select the code, go on 'format' and you can chooose indent region, dedent region and so on

多彩岁月 2024-10-04 13:41:57

您必须使用编辑器命令来重新缩进。

请记住:美丽胜于丑陋。

...以及《Python 之禅》的其余部分,作者:Tim Peters

# python -c "import this"

You have to use an editor command to re-indent.

Keep in mind: Beautiful is better than ugly.

... and the rest of "The Zen of Python, by Tim Peters"

# python -c "import this"
夏天碎花小短裙 2024-10-04 13:41:57

编辑:重写以适应fileinput的“怪癖”*

def indent_code(filename, startline, endline):
    from fileinput import input
    from itertools import izip, count

    all_remaining = count()
    def print_lines(lines, prefix='', range=all_remaining):
        for _, line in izip(range, lines):
            print prefix + line,

    lines = input(filename, inplace=1)
    print_lines(lines, range=xrange(1, startline))  # 1-based line numbers
    print_lines(lines, '    ', xrange(startline, endline + 1)) # inclusive
    print_lines(lines)

def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('filename')
    parser.add_argument('startline', type=int)
    parser.add_argument('endline', type=int)
    ns = parser.parse_args()
    indent_code(ns.filename, ns.startline, ns.endline)

if __name__ == '__main__':
    main()

好吧,或者>}

*:我最初使用 stdout.writelines 和一些生成器表达式的漂亮、简洁的组合来编写此代码。不幸的是,该代码不起作用。 fileinput.input() 返回的迭代器在您调用其 next 方法之前实际上并不打开文件。它同时在 sys.stdout 上发挥其粗略的输出重定向魔法。这意味着,如果您调用 sys.stdout.writelines 并将其传递给 fileinput.input 迭代器,则您的调用和输出将转到原始标准输出,而不是由 fileinput 重新映射到“当前”正在处理的文件。因此,您最终会得到应该替换文件内容的行,而只是打印到终端。

可以通过在调用 stdout.writelines 之前调用 fileinput 迭代器上的 next 来解决此问题,但这会导致其他问题:到达输入文件的末尾会导致其句柄在 file.writelines 内调用时从迭代器的 next 方法关闭。在 Python 2.6 下,此段错误是因为在获取下一个值后,没有进行检查(在实现 writelines 的 C 代码中)来查看文件是否仍然打开,并且文件句柄非零。迭代器。我认为在 2.7 下它只会抛出一个异常,所以这个策略可能在那里起作用。

上面的代码实际上测试正确。

edit: rewrote to accomodate fileinput's "eccentricities"*

def indent_code(filename, startline, endline):
    from fileinput import input
    from itertools import izip, count

    all_remaining = count()
    def print_lines(lines, prefix='', range=all_remaining):
        for _, line in izip(range, lines):
            print prefix + line,

    lines = input(filename, inplace=1)
    print_lines(lines, range=xrange(1, startline))  # 1-based line numbers
    print_lines(lines, '    ', xrange(startline, endline + 1)) # inclusive
    print_lines(lines)

def main():
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('filename')
    parser.add_argument('startline', type=int)
    parser.add_argument('endline', type=int)
    ns = parser.parse_args()
    indent_code(ns.filename, ns.startline, ns.endline)

if __name__ == '__main__':
    main()

Well, either that or >}.

*: I originally wrote this using a nice, concise combination of stdout.writelines and some generator expressions. Unfortunately, that code didn't work. The iterator returned by fileinput.input() doesn't actually open a file until you call its next method. It works its sketchy output-redirection magic on sys.stdout at the same time. This means that if you call sys.stdout.writelines and pass it the fileinput.input iterator, your call, and the output, goes to the original standard out rather than the one remapped by fileinput to the file "currently" being processed. So you end up with the lines that are supposed to replace the contents of the file being instead just printed to the terminal.

It's possible to work around this issue by calling next on the fileinput iterator before calling stdout.writelines, but this causes other problems: reaching the end of the input file causes its handle to be closed from the iterator's next method when called within file.writelines. Under Python 2.6, this segfaults because there's no check made (in the C code which implements writelines) to see if the file is still open, and the file handle non-zero, after getting the next value from the iterator. I think under 2.7 it just throws an exception, so this strategy might work there.

The above code actually does test correctly.

生生不灭 2024-10-04 13:41:57
  • textmate(也许是 e?):选择然后 apple-]
  • bbedit:
    还选择 apple-]
  • emacs:
    选择然后 Mx 'indent-region'
  • bpython:不知道,自动缩进是
    在 bpython 中如此简单,你必须
    努力打破它
  • xcode: don't do python in xcode

这通常是我需要知道的。另外,是的,在一个凹进去的块的上方或下方打一个支架很容易,但你知道一周后当你一天没有盯着它看时,它只会让你感到困惑。非常感谢你们。

  • textmate (and maybe e?): select then apple-]
  • bbedit:
    also select then apple-]
  • emacs:
    select then M-x 'indent-region'
  • bpython: don't know, autoindenting is
    so easy in bpython, you'd have to
    work to break it
  • xcode: don't do python in xcode

that's generally all I need to know. also yeah it's easy to slap a brace above or below a poorly indented block, but you know it's just going to confuse the shit out of you a week later when you haven't been staring at it for like a day. srsly u guys.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文