0

I am having a beginner mistake and i can't see where I have gone wrong.

I am trying to break the program if commandline argument[0] is empty.

I'm running python on macports.

import sys

script = sys.argv[0]
ip = sys.argv[1]
port = sys.argv[2]

if script is None:
    print 'script argv is: ' + script
    break

print "[+] The script name is: " + script
print "[+] The IP is: " +IP+" and the port is: " +port

I keep getting this error.

mars13:python beebs$ python sys.py
  File "sys.py", line 9
    break
SyntaxError: 'break' outside loop

Line 9 refers to break.

1
  • The error is telling you are trying to use a break statement when there is no loop your if statement is not a loop Commented Mar 30, 2015 at 15:38

1 Answer 1

5

break can only be used in a while or for loop; you are trying to use in in an if statement instead.

To exit your script early, use the sys.exit() function.

Note that sys.argv[0] is always going to be a string (in some circumstances it can be an empty string), so if script is None is always going to be false. For your script it'll be set to 'sys.py'.

You should not give your script the same name as a Python standard library module; you named yours sys.py, and only because the module is a built-in and doesn't require loading from a separate file do you get away with that, so in this specific case you were lucky and didn't cause any problems with importing. However, in the general case you'd end up with an import error as your script would be imported instead.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks Martijn! It worked! Now i am getting stuck at ip = sys.argv[1] with error message of IndexError: list index out of range.
@PooT: yes, sys.argv is just a list, and if you don't give command line arguments you'll have a shorter list (at minimum it'll be 1 element long).
@PooT: so you'd check for the length: if len(sys.argv) <= 1: would be true if there is just the script name in the list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.