Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
19 changes: 16 additions & 3 deletions markdownify/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand Down Expand Up @@ -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__':
Expand Down
23 changes: 23 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -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 = "<p>6 \u00f7 2</p>".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"]