1

How to split the string -s -k "test_a or test_b" -m "not unstable" --results=/tmp/test-results --log-cli-level=INFO to

['-s', '-k', 'test_a or test_b', '-m', 'not unstable', '--results=/tmp/test-results', '--log-cli-level=INFO']
Georgy
  • 12,464
  • 7
  • 65
  • 73
anonymous
  • 23
  • 3
  • 3
    It looks there is missing quote after `test_b` – buran Dec 23 '20 at 19:27
  • 3
    From where do you get this string? This seems like command line arguments. This might be an XY-problem as there are some built-in ways to parse command line arguments – Tomerikoo Dec 23 '20 at 19:28

1 Answers1

5

I'm assuming you missed addding a quote. If you want to split with shell-like behaviour, use shlex:

import shlex

s = '-s -k "test_a or test_b" -m "not unstable" --results=/tmp/test-results --log-cli-level=INFO'
print(shlex.split(s))
# ['-s', '-k', 'test_a or test_b', '-m', 'not unstable', '--results=/tmp/test-results', '--log-cli-level=INFO']
Ben
  • 5,952
  • 4
  • 33
  • 44
  • 1
    https://stackoverflow.com/a/899314/6045800 – Tomerikoo Dec 23 '20 at 19:31
  • @anonymous, glad it helps! Also look into the [argparse](https://docs.python.org/3/library/argparse.html) library if you're making a command line tool - it's super handy. If my answer solves your problem, click the check mark to accept it. You should also consider marking this question as a duplicate of https://stackoverflow.com/a/899314/6045800 . Merry Christmas if you celebrate it, Happy Holidays if you don't :) :) – Ben Dec 23 '20 at 19:36
  • If you think it's a duplicate than why do you answer? You have enough rep to close questions, so you should do so – Tomerikoo Dec 23 '20 at 19:40
  • @Tomerikoo, @ anonymous is a new user who is just trying to solve a problem. I encourage them to close this as duplicate, but more than that I want them to get an answer to their question, even though it might not be perfectly efficient or they didn't know how to ask or they should have searched the site for duplicates. – Ben Dec 23 '20 at 19:46
  • @anonymous , it will help you a lot to read https://stackoverflow.com/help/how-to-ask . Get better answers faster for your next question :) – Ben Dec 23 '20 at 19:48
  • 1
    It is alright that they are new and might not find the question. But you are not new. So I just find it funny to suggest to mark a question as duplicate inside an answer. The whole point of duplicates is to ***avoid*** repetition of same questions and answers. Your answer is exactly the same as the answer linked above, where there is even another answer... You're helping the OP by closing their question as duplicate just as much as by answering... – Tomerikoo Dec 23 '20 at 20:37
  • That's a fair point of view – Ben Dec 23 '20 at 20:54