Gribouillis 1,391 Programming Explorer Team Colleague

In the function in_common() when the if fails, there is no return statement, so it returns None.


Also in most situations you don't need if expression == True . Simply write if expression: .

Gribouillis 1,391 Programming Explorer Team Colleague

Hi Gribouillis
thanks for your intervention (I saw your answer just now, guilt spam)
I use Archlinux is a very up to date distro, and it's use python 3.1.2-2 .
It's too difficult to find a solution of this problem?
Or do you know others similar script, without using apache (with php, it's not possible to upload files up 2GB and out of webroot), for a local pc to receive files on my desktop from somewhere with a uploader (webpage) like droopy?

Thanks

byee

On the archlinux site, I see that there is a package python2. You could simply install this package, which would give you a version of python2 on your system and run droopy with this python. You can have several versions of python on the same system.

Gribouillis 1,391 Programming Explorer Team Colleague

I know how to do it using the pari library

>>> from pari import factor
>>> x = 252
>>> g = factor(x, x)
>>> zip(*(eval(str(g[i])[:-1]) for i in (0,1)))
[(2, 2), (3, 2), (7, 1)]
Gribouillis 1,391 Programming Explorer Team Colleague

Use the wait() method on a Threading.Event object or a Threading.Condition object, with a timeout.

Gribouillis 1,391 Programming Explorer Team Colleague

Your question is cryptic. Could you give full examples of input and expected output, and the output you get from your efforts, and possibly your code ? Also read these annoucements http://www.daniweb.com/forums/announcement.php?f=8&announcementid=3 and http://www.daniweb.com/forums/announcement.php?f=8&announcementid=2

Gribouillis 1,391 Programming Explorer Team Colleague

Here is how you should write this

class ECollector:
    #error msg collector
    #this class should be used as 'global'
    def __init__(self):
        self.msgs = []
    def addmsg(self,msg):
        self.msgs.append(msg)
    def clear(self):
        self.msgs = []
class test(ECollector):
    def __init__(self):
        ECollector.__init__(self)
        self.dcodes = []
    def new(self):
        self.addmsg("test!")

You are mistaking classes for class instances (it's like mistaking the dog species for your favorite pet).

Gribouillis 1,391 Programming Explorer Team Colleague

Write a recursive function

# python 2 and 3

def splitmany(s, seps=""):
    if seps:
        u, seps = seps[0], seps[1:]
        for word in s.split(u):
            for item in splitmany(word, seps):
                yield item
    else:
        yield s
            
if __name__ == "__main__":
    print(list(splitmany('hello. world! hello.', "!.")))
    
"""my output -->
['hello', ' world', ' hello', '']
"""

but why don't you want to use regexes ?

Gribouillis 1,391 Programming Explorer Team Colleague

Why do you need to run it with python 3 ? Doesn't your linux system have a python 2 version ?

Gribouillis 1,391 Programming Explorer Team Colleague

I must be using it wrong, I've tried printing the pair, and turning the pair into a list. I don't think the CSV record is compatable? The pair holds:

[('Field', '# Name: module1')]

in the first pass, and

[('Field', '\t\tDATA\t\tDATA\t\t\tDATA\tDATA\tDATA')]

on the second, Assigning the entire record to the right side of the pair.

Can you post an example of your data, and the expected output ?

Gribouillis 1,391 Programming Explorer Team Colleague

Use zip

pairs = zip(itemlist, recordlist)
Gribouillis 1,391 Programming Explorer Team Colleague

Define a score function

def score(item):
    return int(item[0])
z = {'11': [0, 1], '3': [1, -2, 3], '4':[2, 3], '2':[3, -4, 5], '0':[4]}
sorted_z = sorted(z.iteritems(), key=score)
print "z=", sorted_z

for i in range(len(sorted_z)):
     print sorted_z[i][0], " ".join(str(x) for x in sorted_z[i][1])
Gribouillis 1,391 Programming Explorer Team Colleague

Here is a pattern which seems to work

from __future__ import print_function
import re

pat = re.compile(
    r"^(?P<X>\d+)(?:(?: (?P<Y>\d+)/(?P<Z>\d+))|[.](?P<T>\d*))?$"
    )
    
    
def test_pat(data):
    print("TEST_PAT", repr(data))
    match = pat.match(data)
    if not match:
        print("no match")
        return
    for symbol in "XYZT":
        print("%s: %s," % (symbol, repr(match.group(symbol))), end = " ")
    print("")
    
test_pat("3.35")
test_pat("12 2/5")
test_pat("two")

""" my output -->
TEST_PAT '3.35'
X: '3', Y: None, Z: None, T: '35', 
TEST_PAT '12 2/5'
X: '12', Y: '2', Z: '5', T: None, 
TEST_PAT 'two'
no match
"""
Gribouillis 1,391 Programming Explorer Team Colleague

You can use set

x = set(mu1List)
y = set(mu2List)

a = x - y # set of items in x but not in y (set difference)
b = x & y # set of items in both sets (set intersection)
c = y - x # set of items in y but not in x

example

>>> x = set(range(10))
>>> y = set(range(4, 12))
>>> x
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> y
set([4, 5, 6, 7, 8, 9, 10, 11])
>>> x - y
set([0, 1, 2, 3])
>>> x & y
set([4, 5, 6, 7, 8, 9])
>>> y - x
set([10, 11])
>>> x | y
set([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
planetPlosion commented: perfect +3
Gribouillis 1,391 Programming Explorer Team Colleague

Use list comprehensions

>>> L = [ list(range(1+k, 4+k)) for k in range(0,9,3)]
>>> L
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> LL = [x[:2] for x in L] + [[x[0], x[2]] for x in L]
>>> LL
[[1, 2], [4, 5], [7, 8], [1, 3], [4, 6], [7, 9]]
Gribouillis 1,391 Programming Explorer Team Colleague

This one runs

colors = ["blue", "yellow", "red"]
forms = ["triangel", "circle", "square"]
numbers = [1, 2, 3]
grades = [1, 2, 3]
cards = []

for color in colors:
    for form in forms:
        for number in numbers:
            for grade in grades:
                cards.append((color, form, number, grade))

import random
kortutfall = random.sample(cards, 6)

print kortutfall

""" my output -->
[('red', 'circle', 1, 2), ('blue', 'triangel', 1, 2), ('yellow', 'square', 3, 3), ('blue', 'square', 1, 1), ('yellow', 'triangel', 3, 2), ('red', 'circle', 1, 3)]
"""

Hint: don't write code that you don't understand.

Gribouillis 1,391 Programming Explorer Team Colleague
import random
selection = random.sample(cards, 3)
Gribouillis 1,391 Programming Explorer Team Colleague

I've heard only bad things about eval + strings.
Maybe I'm better off not printing them to files?

I need to be able to search out of order in the lists to compare them

for item in List1:
search List2 for item
if match is found
next item
else print item from list1 in file.txt

So, if anyone could help me with this pseudocode.. I haven't found any operators that let me easily compare contents of lists or a search list function

The only 'bad' thing about eval is that you must not eval a string received from the internet, because it could contain arbitrary code which you don't want to execute on your computer.

But there is nothing wrong in evaluating a string written by your own program. It's like running your own script.

planetPlosion commented: straighted my knowledge of eval out +3
Gribouillis 1,391 Programming Explorer Team Colleague

Then modify the code like this

def thefunction():
    filenames = list(x.strip() for x in list(open("name.txt", "rb")) if x.strip())
    L = [(n, open(n, "rb").read()) for n in filenames]
    return [(x, [int(z) for z in y.strip().split()]) for (x,y) in L]
Gribouillis 1,391 Programming Explorer Team Colleague

You can use eval

thelist = eval(open("file.txt").read().strip())
Gribouillis 1,391 Programming Explorer Team Colleague

This should return a list [('filename1.txt', '<content>'), ('filename2.txt', '<content>'), ..]

def thefunction():
    filenames = list(x.strip() for x in list(open("name.txt", "rb")) if x.strip())
    return [(n, open(n, "rb").read()) for n in filenames]
Gribouillis 1,391 Programming Explorer Team Colleague

Use sorted_list = sorted(list1)

Gribouillis 1,391 Programming Explorer Team Colleague

The first error I see is that line 7 should be n = node() .

Gribouillis 1,391 Programming Explorer Team Colleague

Oh, I forgot to mention that I can't copy over another list. I have to do all of it with that 1 list.

Sorry guys.

Then start with the end of the list

def del_odd(l):
  for i in range(len(l)-1, -1, -1):
    if l[i] % 2 != 0:
      del l[i]

Notice that l is a bad variable name. Also try to understand the difference between l.remove(l[i]) (bad) and del l[i] (good).

Gribouillis 1,391 Programming Explorer Team Colleague

Neater than mine probably, but your result does not agree:

""" Result:
Answer is (70600674, (89, 94, 97, 87))
"""

We don't have the same answer because I didn't take the rising diagonals. To take them into account, add yield (x[i+3-k][j+k] for k in four) at line 34 in my solution.

Gribouillis 1,391 Programming Explorer Team Colleague

You are right. But cannot solve every problem in one strike :).
The whole solution to this euler problem is significant shorter. Spoiler

I have an even shorter whole solution

from functools import reduce
from operator import mul
s='''
08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48
'''
data=[[int(cell) for cell in line.split()] for line in s.split("\n") if line]

def gen_tuples(x):
    four = list(range(4))
    for i in range(16):
        for j in range(16):
            yield (x[i][j+k] for k in four)
            yield (x[i+k][j] for k in four)
            yield (x[i+k][j+k] for k in four)

print(max(reduce(mul, t) for t in gen_tuples(data)))
""" my output -->
51267216
"""
Gribouillis 1,391 Programming Explorer Team Colleague

Quote from the wx.PaintDC doc: If you have an EVT_PAINT handler, you must create a wx.PaintDC object within it even if you don't actually use it.. So you should perhaps try

def OnPaint(self, event):
  dc = wx.PaintDC(self)
  sendbf()
Gribouillis 1,391 Programming Explorer Team Colleague

First of all, thank you Gribouillis.
I combine your advice together. The code looks like this:

import subprocess as SP

def children_pid(pid):
    """get the list of the children pids of a pid (linux only)"""    
    proc = SP.Popen('ps -o pid,ppid ax | grep "%d"' % pid, shell=True, stdout=SP.PIPE)
    pidppid  = [x.split() for x in proc.communicate()[0].split("\n") if x]
    return list(int(p) for p, pp in pidppid if int(pp) == pid)
    
term = SP.Popen(["gnome-terminal"])
term.wait()
print term.pid
term.wait()
print children_pid(term.pid)

However, function "children_pid(term.pid)" does not have output except a "[]".
The eventual output is:
2416
[]

Again, I am grateful for your consideration.
Regards.
I am still confused about this problem..

I obtained children pids by running gnome-terminal with the option --disable-factory. I cant help you much because in my mandriva system, the gnome-terminal is destroyed without problem.

Gribouillis 1,391 Programming Explorer Team Colleague

mylist.sort() works, but it sorts the list in place and returns None

>>> L = "the file I'm working with has all text in the same case, case doesn't matter here".split()
>>> print(L)
['the', 'file', "I'm", 'working', 'with', 'has', 'all', 'text', 'in', 'the', 'same', 'case,', 'case', "doesn't", 'matter', 'here']
>>> L.sort()
>>> print(L)
["I'm", 'all', 'case', 'case,', "doesn't", 'file', 'has', 'here', 'in', 'matter', 'same', 'text', 'the', 'the', 'with', 'working']
>>> print(L.sort())
None

Otherwise, you can use newlist = sorted(mylist) which doesn't change the original list, but returns a new list.

Gribouillis 1,391 Programming Explorer Team Colleague

This function may help

def children_pid(pid):
    """get the list of the children pids of a pid (linux only)"""
    import subprocess as SP
    proc = SP.Popen('ps -o pid,ppid ax | grep "%d"' % pid, shell=True, stdout=SP.PIPE)
    pidppid  = [x.split() for x in proc.communicate()[0].split("\n") if x]
    return list(int(p) for p, pp in pidppid if int(pp) == pid)
Gribouillis 1,391 Programming Explorer Team Colleague

Dear all experts,
I tried several options on this issue, such as:

import subprocess, os, signal, time
proc1 = subprocess.Popen("gnome-terminal", shell=True)
print proc1.pid
time.sleep(1.0)
proc1.kill() # or os.kill(proc1.pid, signal.SIGKILL)

The method I used can not kill the child process "proc1". While, if I erase the time.sleep(1.0), it seems like the child process could be killed. But this is not practical though.
In the end, I appreciate all you aids.

The problem is that gnome-terminal starts another (bash) process. For example if I start a gnome-terminal with pid 17873, I also have a bash process with pid 17875. To kill the terminal, one must kill the bash process.
The only way I see to get the bash process' pid is to examine the content of the /proc directory after the gnome-terminal has been launched.
Something like

>>> term = sp.Popen(["gnome-terminal"])
>>> term.wait()
0
>>> print term.pid
18901
>>> # now look in /proc to find the child process (with a pid close to 18901)
Gribouillis 1,391 Programming Explorer Team Colleague

ftplib.error_perm: 552 File not recognized
i: Bad object type: 1

this is what i got...n i learnt that 552 relates to storage allocation exceeded. but my file is only 6,965 KB

It's difficult to help you without the faulty client code.

Gribouillis 1,391 Programming Explorer Team Colleague

You should first check the server by using a standard ftp client like filezilla.

Gribouillis 1,391 Programming Explorer Team Colleague

In a terminal:

$ pydoc xrange

class xrange(object)
 |  xrange([start,] stop[, step]) -> xrange object
 |  
 |  Like range(), but instead of returning a list, returns an object that
 |  generates the numbers in the range on demand.  For looping, this is 
 |  slightly faster than range() and more memory efficient.

AN object like xrange(10) implements the iterator protocol: it has a method __iter__ which returns an object with a __next__ method, so you can write

>>> r = xrange(10)
>>> it = iter(r)
>>> next(it)
0
>>> next(it)
1
>>> next(it)
2

# or
>>> for number in r: ...

but the list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] is never built.
In python 3, range replaces xrange so that

python 2    |  python 3
------------------------
xrange(10)  |  range(10)
range(10)   |  list(range(10))

If you want a python 3 behavior in python 2, you can write

import sys
if sys.version_info < (3,):
    range = xrange
Gribouillis 1,391 Programming Explorer Team Colleague

"i still can't get it to restart the program fully without it showing previous results"
Do you mean that you want the screen to erase the prior input and calculated results? That is tricky if you do it by clearing the screen, but you can do something very simple: At line 33 put this: print('\n'*80) .

You will also want to move the lines that print the header inside the loop. You could use triple quotes:

print("""****************************
  Turf Calculator 0.0.9
****************************""")

or, as an exercise, think about how to write a printHeader(title) function. Hint: The trick I showed with 80 newlines can work for asterisks too, and you can use a calculated value such as bar = '*'*(4+len(title)) .

In linux (or ANSI capable terminal), clear the screen with print("\x1B[2J") .

Gribouillis 1,391 Programming Explorer Team Colleague

temp=1
main_list = [['a', 'b', 'c', 'd'], ['e', 'f'], ['g', 'h']]
for each_list in main_list:
for ctr in range(len(each_list) - 1):
temp=ctr +1
while temp < len(each_list) :
print each_list[ctr],"-", each_list[temp ]
temp = temp + 1;

Please learn about code tags http://www.daniweb.com/forums/announcement.php?f=8&announcementid=3
See how better it looks:

main_list = [['a', 'b', 'c', 'd'], ['e', 'f'], ['g', 'h']]
for each_list in main_list:
    for ctr in range(len(each_list) - 1): 
        temp=ctr +1
        while temp < len(each_list) : 
            print each_list[ctr],"-", each_list[temp ]
            temp = temp + 1;
knan commented: Omg! Thank you so much! Ur a saviour... tyvm :) :) +1
Gribouillis 1,391 Programming Explorer Team Colleague

yes...i got a simple solution..

here s it, hoping it might help some newbie like me:)

if value[:4]== '4501':
print "xxx..whatever..."

What you can do with an object depends entirely on its class. I suspect that your object's class is pyasn1.type.univ.OctetString. You should probably be able to convert the value to a python string by using mystring = str(value) .

Gribouillis 1,391 Programming Explorer Team Colleague

The variables in a function's body are local to this function and can't be used outside the function. The solution is to return the variable and to catch the return value when the function is called

def example(a):
    alist=[]
    alist.append(a)
    print alist
    return alist # <---- return alist to the calling environment

thelist = example(1) # <----- we catch the returned list
print thelist

Note that we could have used the same name alist instead of thelist. I changed the
name to show that we are dealing with 2 different variables.

Gribouillis 1,391 Programming Explorer Team Colleague

Thank you very much. That was very helpful. How am I going to achieve the 1st and 2nd conditions. I am still trying, but i couldnt figure out a regular expression...

You can write pseudo code to build the regular expression. You want to match this

pattern:
    either:
        symbol1 equal symbol2
        newline
        symbol2 equal symbol1
    or:
        symbol3 equal symbol3
    or:
        symbol4 equal symbol5
    newlines (0 or more)

Each of these elements has an equivalent regex pattern:

symbol1 ->  (?P<symbol1>[a-z])
symbol2 ->  (?P<symbol2>[a-z])
repeated symbol1  -> (?P=symbol1)
repeated symbol2  -> (?P=symbol2)
equal -> [=]
newline -> \n
zero or more -> *

This should give you hints to build the regular expression.

knan commented: Thank you very much!! I think i am nearing the answer. +0
Gribouillis 1,391 Programming Explorer Team Colleague

You could also use the strings substitution operator %

keywords = set("TOWN COUNTY".split()) # new keywords can be added here

# helper code

import re
word_re = re.compile(r"\b[a-zA-Z]+\b")

def sub_word(match):
    "helper for create_template"
    word = match.group(0)
    return "%%(%s)s" % word if word in keywords else word

def create_template(format):
    "Transform a user format to a template for the % operator"
    format = format.replace("%", "%%")
    return word_re.sub(sub_word, format)

# end of the helper code

user_format = "COUNTY --- TOWN"
template = create_template(user_format)
print "template: ", template
print "example: ", template % dict(TOWN="Wellsboro", COUNTY="tioga")

"""my output -->
template:  %(COUNTY)s --- %(TOWN)s
example:  tioga --- Wellsboro
"""
Gribouillis 1,391 Programming Explorer Team Colleague

Each module has its own 'namespace', that is to say its own dictionary of known variable names. In your example, the (global) names defined in the module 'usermodule' are 'Image' and 'usermodule. The names defined in the main program are 'image', 'usermodule' and 'imload'.

It means that the function usermodule() doesn't know that there is a variable imload, since it can only see the namespace of the usermodule module. It's an error to use imload in the function's body. Also, another error is that xstart and ystart are not defined anywhere.

The solution is to pass the value of imload to the function through an argument. You can write

# in usermodule.py
def usermodule(imload, x, y):
    return imload[x,y] # imload, x, y are known names in this scope, since they are parameters

# in main program
print usermodule.usermodule(imload, 1,1)
Gribouillis 1,391 Programming Explorer Team Colleague

You could write it this way

MONTH = ['January','Febuary','March','April','May','June','July','August',
            'September','October','November','December']

def highestMonth (rainfall):
    bestMonth, bestValue = 0, rainfall[0]
    for month, value in enumerate(rainfall):
        if value > bestValue:
            bestMonth, bestValue = month, value
    return MONTH[bestMonth], bestValue

def lowestMonth (rainfall):
    bestMonth, bestValue = 0, rainfall[0]
    for month, value in enumerate(rainfall):
        if value < bestValue:
            bestMonth, bestValue = month, value
    return MONTH[bestMonth], bestValue

Note that if you couldn't modify the previous code to find the lowest monthly rainfall, it means that you don't really understand what the code does. If you want to learn python, you must understand what each of these lines of code does exactly. You could add print statements to display the values of the variables, etc.

Gribouillis 1,391 Programming Explorer Team Colleague
Gribouillis 1,391 Programming Explorer Team Colleague

I did try it like that at first but I couldn't quite understand what it wanted and it kept giving me an error. And the code that you posted does not work either (I assume you forgot to close the first mulPoly arguments, so I fixed that). The code you have always gives me an error saying that the lst[0] of the constCoef is out of range. I don't understand how it could be though because it always checks at the start if the list doesn't have any items.

The error is in the shiftRight() function which modifies the list instead of returning a new list. So in the expression addPoly(mulPoly(shiftRight(lst1), shiftLeft(lst2)), scalePoly(constCoef(lst1), lst2)) , the first shiftRight transforms say [3] into [] and then constCoef finds an empty list.

The solution is that shiftRight returns a new list instead of modifying its argument. I changed your code so that none of the functions modifies the lists passed as arguments.

The program runs, it remains to check that it actually computes the product of 2 polynomials

# Standardizes the polynomial (Gets rid of trailing 0s)
def standardize(lst):
    lst = list(lst) # make a copy
    if lst[len(lst)-1] == 0:
        lst.pop()
    return lst

# Finds if the polynomial is 0
def isZeroPoly(lst):
    if lst == []:
        return True
    else:
        return False

# Adds 2 polynomials ([2,3],[4,5] => [6,8])
def addPoly(lst1,lst2):
    result = []
    if len(lst1) > len(lst2):
        for x in range(0,len(lst1)):
            if len(lst2)-1 < x:
                result.append(lst1[x])
            else:
                result.append(lst1[x] + …
Gribouillis 1,391 Programming Explorer Team Colleague

I know, it is hard. I think yours is a good idea, I will see if I can do it. Thanks!

If I may give an advice, write a command line syntax which is familiar to your users. People should be able to start your program without effort.

Gribouillis 1,391 Programming Explorer Team Colleague

You are right, I can take the arguments now. Really appreciated. But when I try to set the third arguments optional, (I am thinking using a conditional clause like, if nargs==2, then c=blah, blah, is this the right way to implement?
Thanks a lot!

I don't know, I think it's unsual to have an option with a variable number of arguments. What you could do is an option with a single argument and allow something like

python arguments.py -M 1,2,3,4 # A single argument, since there is no separating space
or
python arguments.py -M "1, 2, 3, 4" # put the arguments in a string to create a single arg.
Gribouillis 1,391 Programming Explorer Team Colleague

I also tried on OS shell(cmd on windows), this is the error message I got:

Python 2.7 (r27:82525, Jul 4 2010, 09:01:59) [MSC v.1500 32 bit (Intel)] on win
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.getcwd()
'C:\\Python27'
>>> arguments.py -M 1 2 3
File "<stdin>", line 1
arguments.py -M 1 2 3
^
SyntaxError: invalid syntax
Note: "^ " should be under 1 but the format seems not keep after submit.

You must not start the python interactive shell. Simply type python arguments.py -M 1 2 3 in the cmd shell. (Note that your folder C:\Python26 (or other location) must be in your path environment variable).

Gribouillis 1,391 Programming Explorer Team Colleague

Thanks for the code, but it is the same, 1 or every first real argument is highlighted. (The version I am using is Python 2.6)

>>> arguments.py -M 1 2 3
SyntaxError: invalid syntax

>>> opts.multi[0]
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
opts.multi[0]
NameError: name 'opts' is not defined
>>>

I understand, you cannot run the script this way from the python shell, you must call the script from an OS shell (cmd shell on windows, terminal in linux or mac).

Gribouillis 1,391 Programming Explorer Team Colleague

Oh. sorry, here is the traceback message,

>>> commandline.py -M 1 2 3
SyntaxError: invalid syntax
>>>

We probably don't use the same code. Also normally the tracback shows the line where there is the syntax error when there is one. I attach a zip file with the code I'm running.

Gribouillis 1,391 Programming Explorer Team Colleague

Sorry, I mean when I input the file name and some arguments in command-line mode, the error message is always "invalid syntax".
What I did was I saved the code to the python folder, input >>>commandline.py 1 2 3
then I got syntax error each time. Something I totally missed?
Thanks a lot for your corrections.

Please post the traceback. The answer is always in the traceback. Also, if you want to pass arguments to your option -M, you must write commandline.py -M 1 2 3. You should check if opts.multi is None in your code to see if arguments were passed to opts.multi.

There is no syntax error in the code.

Gribouillis 1,391 Programming Explorer Team Colleague

Thanks! I tried the following code, always got error message "invalid syntax", what is the probelm?

def main(args):
    import optparse
    parser = optparse.OptionParser()
    parser.add_option('-M', help='multiple arguments', dest='multi', \
                      action='store', nargs=3)
    (opts, args) = parser.parse_args()

    a=opt.multi[0]
    b=opt.multi[1]
    c=opt.multi[2]

    print "a=", a
    print "b=", b
    print "b=", b

#execute upon command-line invocation
if__name__=="__main__": main(sys.argv)

I corrected your program

def main():
    import optparse
    parser = optparse.OptionParser()
    parser.add_option('-M', help='multiple arguments', dest='multi', \
                      action='store', nargs=3)
    (opts, args) = parser.parse_args()

    a=opts.multi[0]
    b=opts.multi[1]
    c=opts.multi[2]

    print "a=", a
    print "b=", b
    print "c=", c

#execute upon command-line invocation
if __name__=="__main__":
    main()

You must debug your program yourself. Python always tell you where the error occurs in the code, so learn to read an exception traceback.