4

In my code, the following error triggered, and I do not understand how this case can come up:

if(len(sys.argv) > 0):
    doSomething()
else:
    raise AttributeError("Could not parse script name")

The above code is in a python class, which I import and use in some script. I use the same class with the same call in other scripts, and it works just fine everywhere else. FYI, my OS is ubuntu.

How is it even possible that len(sys.argv) is <= 0?

Droids
  • 262
  • 1
  • 9
  • 4
    The number of arguments can't be less than zero, but it can be zero. Example include if your program is started through one of the [POSIX `exec` functions](http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html), where it's possible to not pass any arguments at all including leaving out the "program name" argument. – Some programmer dude Jun 25 '15 at 07:21
  • 1
    @Joachim As far as I understand [the documentation](https://docs.python.org/2/library/sys.html), `argv` should at the very least contain an empty string, for example if it was called in the interactive interpreter. – deceze Jun 25 '15 at 07:22
  • 1
    Can you tell us how the Python script was started/executed when `sys.argv` is empty? Maybe show the call-stack created by the exception you raise? – Some programmer dude Jun 25 '15 at 07:24
  • 3
    You probably accidentally set `sys.argv` elsewhere, for example if you passed the list to some other function that erased the contents. – nneonneo Jun 25 '15 at 07:25
  • @nneonneo You can also modify the list. – Peter Wood Jun 25 '15 at 07:26
  • 1
    Yes, but I'm pointing out something that might be more indirect (and thus less obvious). I've definitely done this before (example: `parse_args(sys.argv)` where `parse_args` `pop`s items off the list). – nneonneo Jun 25 '15 at 07:28
  • 2
    @JoachimPileborg: I actually just tried this (`execve("/usr/bin/python", {NULL}, {NULL}`) and `sys.argv` came back as `['']` (though I verified with a C program that `argc == 0`). So, it looks like you can't get an empty `sys.argv` that way. – nneonneo Jun 25 '15 at 07:31
  • Then it's probably something like @nneonneo mentions, that some other code somewhere modifies `sys.argv`. – Some programmer dude Jun 25 '15 at 07:33

1 Answers1

1

Ok, so we found the answer; @nneonneo gave the right hint, at some point actually argv was modified:

args = sys.argv
del args[0]

I guess the author of that code wanted to do something different, because this actually also deletes sys.argv[0]. We are looking to change it in the following way:

args = sys.argv[1:]

Thank you!

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Droids
  • 262
  • 1
  • 9