I'm making a Network sniffing tool for personal use, and I can't find the syntax error within my code, this is Python 2.7.9 by the way.
Here's the code;
def main():
global listen
global port
global command
global execute
global upload_destination
global target
if not len(sys.argv[1:]):
usage()
#read the commandline options
It says the error is featured below in the next 3 lines, any ideas?
try:
opts, args = getopt.getopt(sys.argv[1:],"hle:t:p:cu:", ¬ ["help","listen","execute","target","port","command","upload"])
except getopt.GetoptError as err:
print str(err)
usage()
I feel there's been a mix up between Python 2 and 3 but I'm not sure.
¬ ["help","listen","execute","target","port","command","upload"])
"¬" This is not valid Python syntax. Removing it should solve the issue.
Also in the future maybe post the actual error which is being shown in the output.
First, this is not valid in programs: ¬. This is Unicode, which basically doesn't work where you placed it all.. Since when does Python allow Unicode as commands in programs? It is not valid and in the wrong place. Now doing this will work:
print "¬"
It's a string so nothing wrong but the usage in your program makes that a Syntax error as there is no such command called ¬. Also, in the try statement, you have an indention of 8 spaces. You can only use 4 or 2-space indention in your programs.
EDIT: Okay, you can use 8-space indention in programs but you need to use 8 (or a multiple of 8) spaces every single line you need to indent. Since your indention is non-consistent, that could also be the reason you are getting an error.
Related
First of all, I want to apologize for even trying to do this. I know that it's not recommended in any way. However, external constraints leave me little other choice than to go this path.
I have a piece of python code that lies on a read-only filesystem. I cannot move it. I cannot modify it. It has an inconsistent use of tabs and spaces. And I need this code to be importable with the -tt option.
Is there any way to ignore the -tt option for a specific import statement, a specific code section, or a certain application altogether?
I fully admit that this is a horrible, horrible solution. I await the downvotes:
dodgymodule.py:
def somefunc():
print("This is indented using 4 spaces")
print("This is indented using a tab")
main python script, which uses autopep8 to fix the code and import the resulting string instead:
import autopep8
import imp
try:
import dodgymodule
except TabError as e:
with open(e.filename, 'r') as f:
new_module_contents = autopep8.fix_code(f.read())
dodgymodule = imp.new_module('dodgymodule')
exec(new_module_contents, dodgymodule.__dict__)
dodgymodule.somefunc()
python3 -tt script.py prints out the lines, as hoped.
I'm an experienced C++ developer, but am just getting my feet wet with Python for a project at work. I'm having some basic problems and Google has been less than helpful. I suspect something about my environment is funny, but I have no clue how to diagnose it. I wrote a simple script that merely prints an argument to the screen, but I am getting an error when running it (python args.py):
Syntax Error: invalid syntax
File "args.py", line 4
print arg0
For reference, there is a carrot underneath the 0 of arg0. The script in question:
import sys
firstArg = sys.argv[0]
print firstArg
I'm sure this is something really dumb, but Python is such a foreign thing, coming from C++.
This seems pretty obvious. The traceback says you have a SyntaxError on line 4, therefore print firstArg isn't valid Python.
The not obvious part is that a lot of examples on the Internet use syntax like that. This is because in Python 2.X versions, print was a statement. Since Python 3.0, print is a function. Try print(firstArg) instead.
Protip: If you want to enable the print function in Python 2, use from __future__ import print_function.
I can understand that the print function of Python may be different for C or C++ developers because of its features.
The syntax that you use is for python 2 (now in End Of Life status). There are many differences between Python 2 and python 3.
In this case, the print was a statement in Python 2 but function in Python3.
Here is the correct syntax for print function in Python3.
print(firstArg)
Brackets are important because print is a function. The print function in Python has some parameters which make it even more powerful.
I'm testing out some argparse code. I wanted to have an optional argument, which collects n number of inputs from a list of choices. So, I wrote:
import argparse
modules = ["geo", "loc"]
parser = argparse.ArgumentParser()
parser.add_argument("--modules", nargs='*', choices=modules)
With this set up, I'm reliably able to kill the interpreter completely.
It works fine if you pass a valid set of arguments:
>>> parser.parse_args("--module geo loc geo".split())
Namespace(modules=['geo', 'loc', 'geo'])
But if you pass in a miss formed argument, it kills python completely:
>>> parser.parse_args("--module geo metro".split())
usage: [-h] [--modules [{geo,loc} [{geo,loc} ...]]]
: error: argument --modules: invalid choice: 'metro' (choose from 'geo', 'loc')
PS C:\Users\myname\mycode>
My question is two-fold:
Is this expected behavior? If so, what is the reasoning for this?
Will I be okay using this code, since I don't mind if my program dies with ill-formed arguments? Or is there some compelling reason to avoid this?
As a note, I am using Python2.7 on Windows 7.
Yes, this is intended, and documented:
While parsing the command line, parse_args() checks for a variety of errors, including ambiguous options, invalid types, invalid options, wrong number of positional arguments, etc. When it encounters such an error, it exits and prints the error along with a usage message:
The idea is that, if the user gives an invalid option or argument which you don't know how to handle, the best option is to give up instead of second-guess the user's actual intentions.
If you don't mind, then it should be ok, right? Unless you know a reason to implement different behavior, your program is completely consistent with all well-behaved command line tools on all platforms.
If you do want to implement different behavior, catch the SystemExit exception that parse_args might raise.
(The only program that I can think of that behaves differently from the way I just described is the version control tool Git, which does try to guess what the user meant and prints its guesses. It then still exits, though.)
argparse is designed for use when your Python script is run from a command line. That's why invalid arguments cause the program to quit.
This behavior is consistent with virtually all shell (bash/sh/dos/etc.) utilities. Invalid command line args cause the program to quit with an error string and (optionally) a usage message.
Where can I find information about meaning of exit codes of "python" process on Unix? For instance, if I do "python thisfiledoesntexist.py", I get exit code 2
Summary:
from errno import errorcode
print errorcode[2]
As stated, mostly the error codes come from the executed script and sys.exit().
The example with a non-existing file as an argument to the interpreter fall in a different category. Though it's stated nowhere I would guess, that these exit codes are the "standard" Linux error codes. There is a module called errno that provides these error numbers (the exit codes come from linux/include/errno.h.
I.e.: errno.ENOENT (stands for for "No such file or directory") has the number 2 which coincides with your example.
The Python manual states this regarding its exit codes:
Some systems have a convention for assigning specific meanings to specific exit codes, but these are generally underdeveloped; Unix programs generally use 2 for command line syntax errors and 1 for all other kind of errors.
So, since you specified thisfiledoesntexist.py as a command line argument, you get a return code of 2 (assuming the file does not, in fact, exist. In that case I'd recommend renaming it to thisfiledoesexist.py. ;) )
Other that such parsing errors, the return code is determined by the Python program run. 0 is returned unless you specify another exit code with sys.exit. Python itself does not interfere.
Maybe exit code constants from os module can help you. Also have a look at sys.exit documentation.
Unfortunately, there is no 100% guarantee that Python's exit codes will be what the documentation claims they will be: os._exit allows the Python programmer to define which exit code is supposed to be used, which means python file_exists_but_claims_that_it_does_not.py could exit with os.EX_DATAERR.
I have not had much luck hunting for finding a good explanation of what invalid argument errors are and what would cause them.
My current sample I am working with is
import sys
mylog="mylog.log"
sys.stdout = open(mylog,'w')
#lots of code
#.
#.
#.
#End of lots of code
from time import clock
print "blablabla",clock()
I receive an IOError Invalid Argument error on the clock line. I have also tried
print "blablabla\t%s"%clock()
Any information about this error would be great help. Those lines work perfectly fine on short runs, it just after running the code for a while it breaks. I have tried to setting the buffer size to something low like 45-100 lines.
I can't reproduce this exact problem on my own computer, so I can't give specific advice, but here is some general commentary on how to debug this sort of thing.
When you see "Invalid argument" in an IOError or OSError exception from python, that means the interpreter tried to make a system call, which failed and set errno to the code EINVAL. (Tangentially, python really shouldn't print the numeric values for errno codes - the symbolic names are standardized but the numbers aren't.) The first thing you need to do is find out which system call it was, and the easiest way to do that is run your program under the strace utility, like this:
$ strace -f -o strace.log python yourscript.py [arguments...]
Wait for it to fail, then search the file strace.log for "-1 E" (exactly that string). You will find something like this:
times({tms_utime=162, tms_stime=123, tms_cutime=0, tms_cstime=0}) = 1718279979
write(1, "2.85\n", 5) = -1 EINVAL (Invalid argument)
You then read the man page for the system call that failed ("man 2 write" in this case) and look for the errno code name (EINVAL in this case), and see what it says has gone wrong.
In this case I strongly suspect you have found a bug in either the Python interpreter or the operating system. "Invalid argument" means what it says - one of the input arguments to the system call had an invalid value. You're not doing anything tricky in your script, so either the interpreter is messing up its system calls, or the kernel misunderstood what the interpreter wanted.