Created
April 26, 2017 16:42
-
-
Save graphaelli/05bc7d49b36e2cab06e7c63780bf1093 to your computer and use it in GitHub Desktop.
quote a list of inputs, mostly for use in sql queries
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from io import StringIO | |
import argparse | |
import sys | |
import unittest | |
def quote_list(r, sep=None): | |
# hope r is smallish | |
return ", ".join("'{}'".format(t) for t in r.read().split(sep=sep)) | |
class TestLineSep(unittest.TestCase): | |
expected = ( | |
"'1', '2', '3'" | |
) | |
def test_commas(self): | |
self.assertEqual(self.expected, quote_list(StringIO("1,2,3"), ',')) | |
def test_newline(self): | |
self.assertEqual(self.expected, quote_list(StringIO("1\n2\n3\n"))) | |
self.assertEqual(self.expected, quote_list(StringIO("1\n2\n3"))) | |
def test_whitespace(self): | |
self.assertEqual(self.expected, quote_list(StringIO("1 2 3"))) | |
self.assertEqual(self.expected, quote_list(StringIO("1 2 3 "))) | |
def main(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument('-f', '--field-separator', default=None, type=str) | |
parser.add_argument('input', type=argparse.FileType('r')) | |
args = parser.parse_args() | |
print(quote_list(args.input, args.field_separator)) | |
if __name__ == '__main__': | |
if sys.stdin.isatty() and len(sys.argv) > 1 and sys.argv[1] == 'test': | |
sys.argv.pop(1) | |
unittest.main() | |
else: | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment