【问题标题】:How can I use JSBeautify from the command line?如何从命令行使用 JSBeautify?
【发布时间】:2012-09-23 06:54:45
【问题描述】:

我喜欢jsbeautifier.org,我看到他们有一个github repo 和他们的代码。

自述文件中有两个如何通过命令行使用此工具的示例:

import jsbeautifier
res = jsbeautifier.beautify('your javascript string')
res = jsbeautifier.beautify_file('some_file.js')

和:

opts = jsbeautifier.default_options()
opts.indent_size = 2
res = jsbeautifier.beautify('some javascript', opts)

如何将其合并到脚本 (myjsbeautify.py) 中,以便它可以接受 stdin 或参数(文件名)并输出到 stdout ?我也想使用keep array indentation的选项。

所需的语法

cat ugly.js | myjsbeautify.py

myjsbeautify.py ugly.js

【问题讨论】:

    标签: python shell command-line js-beautify


    【解决方案1】:

    查看this post 了解如何将 JSBeautify 与 Textmate 结合使用。它有一些关于如何在您的系统上安装它的很好的说明。在 Mac OS X 上,我使用:

    cd /tmp
    git clone https://github.com/einars/js-beautify.git
    cd js-beautify/python
    python setup.py install
    

    然后你可以简单地使用js-beautify /path/to/filename.js 让它运行。

    【讨论】:

    • 我也必须这样做easy_install six
    【解决方案2】:

    您的示例是用作库而不是命令行。如果您尝试自己创建一个可以接受参数并将其传递给 JSBeautifier 的脚本,您应该查看argparse 模块。它有一些很好的例子可以帮助你前进。 来自文档的示例:

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('infile', nargs='?', type=argparse.FileType('r'),
    ...                     default=sys.stdin)
    >>> parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
    ...                     default=sys.stdout)
    >>> parser.parse_args(['input.txt', 'output.txt'])
    Namespace(infile=<_io.TextIOWrapper name='input.txt' encoding='UTF-8'>,
              outfile=<_io.TextIOWrapper name='output.txt' encoding='UTF-8'>)
    >>> parser.parse_args([])
    Namespace(infile=<_io.TextIOWrapper name='<stdin>' encoding='UTF-8'>,
              outfile=<_io.TextIOWrapper name='<stdout>' encoding='UTF-8'>)
    

    编辑:您还可以使用getopt 本身使用的jsbeautifier.py。如果你只是想将jsbeautifier.py用作命令行工具,请阅读源代码中的usage函数。

    【讨论】:

      【解决方案3】:

      一般来说,您可以使用fileinput 模块,它允许您从标准输入或位置参数中命名的文件中读取。

      【讨论】:

        【解决方案4】:

        我刚刚做了pip install jsbeautify,它在我的路径中添加了js-beautify (/usr/local/bin/js-beautify)。

        你可以按照你的期望使用它:

        js-beautify --keep-array-indentation file.json > file.pretty.json
        

        并使用帮助来检查更多参数:

        js-beautify --help
        

        【讨论】:

          猜你喜欢
          • 2010-11-30
          • 2011-10-17
          • 2015-09-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-25
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多