Skip to content

Commit

Permalink
Parse command out of most Python command lines
Browse files Browse the repository at this point in the history
  • Loading branch information
walles committed Mar 25, 2016
1 parent 987b9c6 commit 716dc97
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
19 changes: 19 additions & 0 deletions px/px_commandline.py
Expand Up @@ -57,4 +57,23 @@ def get_command(commandline):
# next to last part
command = command_split[-2]

if command in ['python', 'Python']:
return get_python_command(commandline)

return command


def get_python_command(commandline):
array = to_array(commandline)
python = os.path.basename(array[0])
if len(array) == 1:
return python

if not array[1].startswith('-'):
return os.path.basename(array[1])

if len(array) > 2:
if array[1] == '-m' and not array[2].startswith('-'):
return os.path.basename(array[2])

return python
8 changes: 6 additions & 2 deletions px/px_commandline_test.py
Expand Up @@ -8,17 +8,21 @@ def test_get_command_python():

# These are inspired by Python 2.7.11 --help output
assert px_commandline.get_command("python apa.py") == "apa.py"
assert px_commandline.get_command("python /usr/bin/apa.py") == "apa.py"
assert px_commandline.get_command("python /usr/bin/hej") == "hej"
assert px_commandline.get_command("python /usr/bin/hej gris --flaska") == "hej"
assert px_commandline.get_command("python -c cmd") == "python"
assert px_commandline.get_command("python -m mod") == "mod"
assert px_commandline.get_command("python -m mod --hej gris --frukt") == "mod"
assert px_commandline.get_command("Python -") == "Python"

assert px_commandline.get_command("python -W warning:spec apa.py") == "apa.py"
assert px_commandline.get_command("python -u -t -m mod") == "mod"
# To begin with, any switches other than -c -m or - and we give up. Room for
# future improvement.
assert px_commandline.get_command("python -W warning:spec apa.py") == "python"
assert px_commandline.get_command("python -u -t -m mod") == "python"

# Invalid command lines
assert px_commandline.get_command("python -W") == "python"
assert px_commandline.get_command("python -c") == "python"
assert px_commandline.get_command("python -m") == "python"
assert px_commandline.get_command("python -m -u") == "python"

0 comments on commit 716dc97

Please sign in to comment.