struggling with Import Sys

Viewed 25

I'm brand new to coding and I'm trying to get my code to work in the command line so that when I type python3 filename.py The World is big - it returns the the first smallest word on the next lines.

I know that I'm over-thinking this but I really need a dummies version of how to know where to put the sys.argv to make this work. I'll put a very simple code that I have tried different ways and just don't know where to put it. I have to enter the string on the line before it gives me the answer.



import sys

text = input("")

short = min(text.split(), key=len)

print("Shortest word is: ", short)
1 Answers

According to the docs:

The list of command line arguments passed to a Python script. argv[0] is the script name.

So you could directly get the inputs from sys.argv. E.g.

import sys

print(sys.argv)

# python filename.py "The World is big"
# prints:
# ['filename.py', 'The World is big']

Note that the arguments passed in the example above is quoted, making it a single string argument. Running python filename.py The World is big would pass each word as a single argument.

# python filename.py The World is big
# prints:
# ['filename.py', 'The', 'World', 'is', 'big']
Related