Development Tip

Python 코드의 들여 쓰기를 중괄호로 변환하는 방법이 있습니까?

yourdevel 2020. 10. 5. 21:04
반응형

Python 코드의 들여 쓰기를 중괄호로 변환하는 방법이 있습니까?


저는 파이썬을 배우고 싶은 완전히 맹목적인 프로그래머입니다. 불행히도 코드 블록이 서로 다른 수준의 들여 쓰기로 표현된다는 사실은 큰 걸림돌입니다. 중괄호 또는 다른 코드 블록 구분 기호를 사용하여 코드를 작성한 다음 해당 형식을 Python 인터프리터가 사용할 수있는 적절하게 들여 쓰기 된 표현으로 변환 할 수있는 도구가 있는지 궁금합니다.


파이썬 자체와 함께 배포되는 문제에 대한 해결책이 있습니다. pindent.py, Windows 설치의 Tools \ Scripts 디렉토리에 있습니다 (내 경로는 C : \ Python25 \ Tools \ Scripts). 실행중인 경우 svn.python.org에서 가져와야하는 것처럼 보입니다 . Linux 또는 OSX.

블록이 닫힐 때 주석을 추가하거나 주석이 삽입 된 경우 코드를 적절하게 들여 쓰기 할 수 있습니다. 다음은 명령을 사용하여 pindent에 의해 출력되는 코드의 예입니다.

pindent.py -c myfile.py

def foobar(a, b):
   if a == b:
       a = a+1
   elif a < b:
       b = b-1
       if b > a: a = a-1
       # end if
   else:
       print 'oops!'
   # end if
# end def foobar

원본 위치 myfile.py:

def foobar(a, b):
   if a == b:
       a = a+1
   elif a < b:
       b = b-1
       if b > a: a = a-1
   else:
       print 'oops!'

pindent.py -r주석 (자세한 내용은 pindent.py의 헤더 참조)을 기반으로 올바른 들여 쓰기를 삽입하는 데 사용할 수도 있습니다. 이렇게 하면 들여 쓰기에 대해 걱정하지 않고 파이썬으로 코딩 할 수 있습니다.

예를 들어, pindent.py -r myfile.py다음 코드를 실행 하면 myfile.pypindent.py -c예제에서 생성 된 것과 동일한 적절한 들여 쓰기 (및 주석 처리 된) 코드로 다음 코드가 변환됩니다 .

def foobar(a, b):
if a == b:
a = a+1
elif a < b:
b = b-1
if b > a: a = a-1
# end if
else:
print 'oops!'
# end if
# end def foobar

어떤 솔루션을 사용하게되는지 알고 싶습니다. 추가 지원이 필요한 경우이 게시물에 의견을 남겨 주시면 도움을 드리겠습니다.


많은 파이썬 애호가들이 파이썬이 이런 식이고 공백으로 구분된다는 사실을 좋아하기 때문에 저는 개인적으로 현재 현재가 있는지 의심합니다.

그러나 실제로 접근성 문제로 생각한 적이 없습니다. 아마도 파이썬에 버그 보고서로 제출할 것입니까?

그러나 출력을 위해 스크린 리더를 사용한다고 가정합니다. 그러면 탭이 "보이지 않는"것처럼 보일까요? 점자 출력을 사용하면 읽기가 더 쉬울 수 있지만 이것이 얼마나 혼란 스러울 수 있는지 정확히 이해할 수 있습니다.

사실 이것은 나에게 매우 흥미 롭습니다. 이 작업을 수행 할 수있는 앱을 작성할 수있을만큼 충분히 알고 있었으면합니다.

당신이 이미 직접 해본 적이 없거나 원치 않는 한, 확실히 버그 리포트에 넣을 것이라고 생각합니다.

편집 :로 또한 언급 에 의해 존 밀리 킨 도있다 PyBraces 당신에게 실행 가능한 해결책이 될 수 있으며 가능하다 해킹 받아야합니다 정확히 무엇을 할 수 코딩 기술에 함께 따라 (그리고 나는 그런 경우 희망 , 자신과 같은 다른 사람이 사용할 수 있도록 공개)

편집 2 : 방금 파이썬 버그 추적기에 이것을보고했습니다.


맹인은 아니지만 Emacspeak에 대해 좋은 소식을 들었습니다 . 1998 년 8.0 릴리스 이후로 Python 모드 를 사용했습니다 (28.0 릴리스까지 올라간 것 같습니다!). 확실히 확인할 가치가 있습니다.


탭과 공백을 말하도록 편집기를 구성 할 수 있어야합니다 . 대부분의 편집기에서 공백 표시 할 수 있다는 것을 알고 있으므로이를 말할 수있는 접근성 옵션이 있어야합니다.

실패하면 pybraces있는데 , 이는 실용적인 농담으로 작성되었지만 실제로는 약간의 작업으로 유용 할 수 있습니다.


If you're on Windows, I strongly recommend you take a look at EdSharp from: http://empowermentzone.com/EdSharp.htm It supports all of the leading Windows screenreaders, it can be configured to speak the indentation levels of code, or it has a built in utility called PyBrace that can convert to and from braces syntax if you want to do that instead, and it supports all kinds of other features programmers have come to expect in our text editors. I've been using it for years, for everything from PHP to JavaScript to HTML to Python, and I love it.


I appreciate your problem, but think you are specifying the implementation instead of the problem you need solved. Instead of converting to braces, how about working on a way for your screen reader to tell you the indentation level?

For example, some people have worked on vim syntax coloring to represent python indentation levels. Perhaps a modified syntax coloring could produce something your screen reader would read?


All of these "no you can't" types of answers are really annoying. Of course you can.

It's a hack, but you can do it.

http://timhatch.com/projects/pybraces/

uses a custom encoding to convert braces to indented blocks before handing it off to the interpreter.


As an aside, and as someone new to python - I don't accept the reasoning behind not even allowing braces/generic block delimiters ... apart from that being the preference of the python devs. Braces at least won't get eaten accidentally if you're doing some automatic processing of your code or working in an editor that doesn't understand that white space is important. If you're generating code automatically, it's handy to not have to keep track of indent levels. If you want to use python to do a perl-esque one-liner, you're automatically crippled. If nothing else, just as a safeguard. What if your 1000 line python program gets all of its tabs eaten? You're going to go line-by-line and figure out where the indenting should be?

Asking about it will invariably get a tongue-in-cheek response like "just do 'from __ future __ import braces'", "configure your IDE correctly", "it's better anyway so get used to it" ...

I see their point, but hey, if i wanted to, i could put a semicolon after every single line. So I don't understand why everyone is so adamant about the braces thing. If you need your language to force you to indent properly, you're not doing it right in the first place.

Just my 2c - I'm going to use braces anyway.


Searching an accessible Python IDE, found this and decided to answer. Under Windows with JAWS:

  1. Go to Settings Center by pressing JawsKey+6 (on the number row above the letters) in your favorite text editor. If JAWS prompts to create a new configuration file, agree.
  2. In the search field, type "indent"
  3. There will be only one result: "Say indent characters". Turn this on.
  4. Enjoy!

The only thing that is frustrating for us is that we can't enjoy code examples on websites (since indent speaking in browsers is not too comfortable — it generates superfluous speech).

Happy coding from another Python beginner).


I use eclipse with the pydev extensions since it's an IDE I have a lot of experience with. I also appreciate the smart indentation it offers for coding if statements, loops, etc. I have configured the pindent.py script as an external tool that I can run on the currently focused python module which makes my life easier so I can see what is closed where with out having to constantly check indentation.


There are various answers explaining how to do this. But I would recommend not taking this route. While you could use a script to do the conversion, it would make it hard to work on a team project.

My recommendation would be to configure your screen reader to announce the tabs. This isn't as annoying as it sounds, since it would only say "indent 5" rather than "tab tab tab tab tab". Furthermore, the indentation would only be read whenever it changed, so you could go through an entire block of code without hearing the indentation level. In this way hearing the indentation is no more verbose than hearing the braces.

As I don't know which operating system or screen reader you use I unfortunately can't give the exact steps for achieving this.


Edsger Dijkstra used if ~ fi and do ~ od in his "Guarded Command Language", these appear to originate from the Algol68. There were also some example python guarded blocks used in RosettaCode.org.

fi = od = yrt = end = lambda object: None;
class MyClass(object):
    def myfunction(self, arg1, arg2):
        for i in range(arg1) :# do
            if i > 5 :# then
                print i
            fi
        od # or end(i) #
    end(myfunction)
end(MyClass)

Whitespace mangled python code can be unambiguously unmangled and reindented if one uses guarded blocks if/fi, do/od & try/yrt together with semicolons ";" to separate statements. Excellent for unambiguous magazine listings or cut/pasting from web pages.

It should be easy enough to write a short python program to insert/remove the guard blocks and semicolons.

참고URL : https://stackoverflow.com/questions/118643/is-there-a-way-to-convert-indentation-in-python-code-to-braces

반응형