Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to apply yapf to every python file under a directory?

I have installed Google yapf (yet another python formatter) under a project and try to format all my python files in-place, however I got the following error:

$ yapf -i -r files **.py
yapf: Input filenames did not match any python files

why yapf is incapable of understanding pattern? What should I do to achieve the same thing?

EDIT I also tried yapf -ir as suggested but I got:

$ yapf -ir
usage: yapf [-h] [-v] [-d | -i] [-r | -l START-END] [-e PATTERN]
            [--style STYLE] [--style-help] [--no-local-style] [-p] [-vv]
            [files [files ...]]
yapf: error: cannot use --in-place or --diff flags when reading from stdin

which is strange as I'm not reading from stdin

like image 713
tribbloid Avatar asked Nov 18 '18 03:11

tribbloid


People also ask

How do you use YAPF in Python?

To format a given file you may use yapf -i path/to/file.py . To automatically format any Python files you have changed prior to commiting you may use the command: git diff --name-only --cached | grep '\. py' | xargs yapf -i . This will in place format any files with the .

What is YAPF?

YAPF takes a different approach. It's based off of 'clang-format', developed by Daniel Jasper. In essence, the algorithm takes the code and reformats it to the best formatting that conforms to the style guide, even if the original code didn't violate the style guide.


1 Answers

The first problem is that wildcard expansion happens in the shell, before the command line even executes. When you run:

somecommand *.py

That command doesn't know you typed a *. All it knows is that you passed in a list of files. In other words, yapf is incapable of understanding the pattern because it never sees the pattern.

The second problem is that ** isn't a valid shell file globbing pattern. That's semantically equivalent to *, so running yapf -ir files **.py will only process any .py files contained in your current directory and inside the files directory.

If you want to run yapf recursively on all your Python files, starting in your current directory, there are a few solutions. The simplest is probably:

yapf -ir .

This will process all .py files in your current directory and its children. If you want more control over the selection of files, use find and xargs:

find . -name '*.py' -print0 | xargs -0 yapf -i
like image 177
larsks Avatar answered Sep 20 '22 13:09

larsks