diff --git a/README.rst b/README.rst index 059a68f..37020b8 100644 --- a/README.rst +++ b/README.rst @@ -240,6 +240,8 @@ Use ``markdownify example.html > example.md`` or pipe input from stdin (``cat example.html | markdownify > example.md``). Call ``markdownify -h`` to see all available options. They are the same as listed above and take the same arguments. +For HTML in a known encoding, use e.g. ``markdownify --input-encoding latin-1 example.html``. +The option also applies to piped input. Development diff --git a/markdownify/main.py b/markdownify/main.py index ba70671..ca7c028 100755 --- a/markdownify/main.py +++ b/markdownify/main.py @@ -13,10 +13,11 @@ def main(argv=sys.argv[1:]): description='Converts html to markdown.', ) - parser.add_argument('html', nargs='?', type=argparse.FileType('r'), - default=sys.stdin, + parser.add_argument('html', nargs='?', default='-', help="The html file to convert. Defaults to STDIN if not " "provided.") + parser.add_argument('--input-encoding', + help="Encoding of the HTML file or standard input.") parser.add_argument('-s', '--strip', nargs='*', help="A list of tags to strip. This option can't be used with " "the --convert option.") @@ -77,7 +78,19 @@ def main(argv=sys.argv[1:]): "'html5lib'.") args = parser.parse_args(argv) - print(markdownify(**vars(args))) + options = vars(args) + path = options.pop('html') + encoding = options.pop('input_encoding') + if path == '-' and encoding is None: + html = sys.stdin.read() + else: + try: + source = sys.stdin.fileno() if path == '-' else path + with open(source, encoding=encoding, closefd=path != '-') as stream: + html = stream.read() + except (OSError, LookupError, UnicodeError) as error: + parser.error(str(error)) + print(markdownify(html, **options)) if __name__ == '__main__': diff --git a/tests/test_cli.py b/tests/test_cli.py new file mode 100644 index 0000000..5406b1a --- /dev/null +++ b/tests/test_cli.py @@ -0,0 +1,23 @@ +import os +import subprocess +import sys + +import pytest + + +@pytest.mark.parametrize("source", ["file", "stdin", "dash"]) +def test_input_encoding(tmp_path, source): + html = "
6 \u00f7 2
".encode("iso-8859-1") + argv = [sys.executable, "-m", "markdownify.main", "--input-encoding", "iso-8859-1"] + if source == "file": + path = tmp_path / "input.html" + path.write_bytes(html) + argv.append(str(path)) + elif source == "dash": + argv.append("-") + + output = subprocess.check_output( + argv, input=html if source != "file" else b"", + env=dict(os.environ, PYTHONIOENCODING="utf-8", PYTHONUTF8="1"), + ) + assert output.decode("utf-8").splitlines() == ["6 \u00f7 2"]