but regarding php , i would like to know how node.js stands against it.
This question should perhaps be asked in a web development forum, php, javascript ... ?
but regarding php , i would like to know how node.js stands against it.
This question should perhaps be asked in a web development forum, php, javascript ... ?
Let us try without shell, try
import shlex
args = shlex.split(command)
print args
sh=sp.Popen(args, stdout=sp.PIPE, stderr=sp.PIPE, shell=False)
print sh.communicate()
print "return code was %d" % sh.returncode
what happens, and what is the output ?
Please remove the wait() and post what gets printed ! A return code of 0 means a successful command.
Another possibility is that the matlab command returns immediately and starts another process which is the actual matlab. When you launch the command in a terminal, can you use the terminal while matlab is running ? (try the ls command for example)
Try
sh=sp.Popen(command, stdout=sp.PIPE, stderr=sp.PIPE, shell=True)
sh.wait()
print sh.communicate()
print "return code was %d" % sh.returncode
You can remove the stdin argument as you don't send data to the subprocess. The communicate() method
should block until the matlab program returns, and it should return the output string and error string
of this process. What gets printed when you write
sh=sp.Popen(command, stdout=sp.PIPE, stderr=sp.PIPE, shell=True)
print sh.communicate()
print "return code was %d" % sh.returncode
?
The first thing to check is what happens when you run the command
/Applications/MATLAB_R2012b.app/bin/matlab -r "cd(fullfile('/Users/Jules/Dropbox/CODES/Matlab/')), coverGUI_AL_FOV"
in an ordinary terminal (without python).
For the off topic question, read this help .
To make short take any of efficiency, code size, memory effort, programming effort, then
c++ > java > python
Python is easier because it uses duck typing. Java is easier than C++ because of memory management and types management.
c# is very similar to java. Perl has ugly and unmaintainable code.
This can be understood mainly by examining the history of these languages. C++ was an object oriented development of C at the time where OOP was the new paradigm. Perl started as a system scripting language which was more structured than shell languages. It was then heavily used when internet was based on cgi scripts and there was no other alternative. Php succeeded because it made it possible to include dynamic code in html pages.
Python is different. It started as a general purpose language derived from a small university language called ABC. Its success comes from experience: people realized that using python led to drastic cuts in their programming effort!
$ pydoc sum
Help on built-in function sum in module __builtin__:
sum(...)
sum(sequence[, start]) -> value
Returns the sum of a sequence of numbers (NOT strings) plus the value
of parameter 'start' (which defaults to 0). When the sequence is
empty, returns start.
(END)
Given the menu-based structure of your program, you may find some reusable ideas in this snippet that I wrote a long time ago to help menu based scripts writers!
What is your question with regard to this ambitious project ?
AttributeError: 'NoneType' object has no attribute 'get' .
I think the place()
method returns the None object, so that one must not write
entry = ttk.Entry(...).place(...)
tailles_entry.append(entry)
but
entry = ttk.Entry(...)
entry.place(...)
tailles_entry.append(entry)
Here is a first working version
#/usr/bin/env python
# -*-coding: utf8-*-
from Tkinter import *
import Tkinter as tk
import os
import ttk
b = ["S","M","L"]
qtetaillevar = b
tailles_entry = []
def valider():
for i in range(len(b)):
qtetaillevar[i] = tailles_entry[i].get()
print qtetaillevar[i]
def Interface2() :
interf2 = Tk()
interf2.geometry("500x400")
interf2.title(' Gestion du Depot ')
f1 = Frame(interf2, bg="blue", width=500, height=700)
f1.pack( fill=X, expand=0)
lab2 = Label(interf2, text="Veuillez saisir le numero d'Import du Model ( num+année , ex: 122013 )\n et cliquer sur valider " , bg = "blue", fg = "white" )
lab2.place ( x=80 , y=45 )
distligne = 0
for i in range(len(b)):
qtetaillevar[i] = StringVar()
distligne = 30 + distligne
entry = ttk.Entry(interf2, width=13, textvariable=qtetaillevar[i])
entry.place (x = 130 , y = 165+distligne)
tailles_entry.append(entry)
bou_valider = Button(interf2, text = " Valider ", command = valider)
bou_valider.place( x=250, y=100)
interf2.mainloop()
Interface2()
Ok, if you want to create a number of entries, use a list and a loop
nbr_entries = len(b)
tailles_entry = [] # a list
for i in range(nbr_entries):
entry = ttk.Entry(interf2, width=13)
tailles_entry.append(entry) # add a new entry to the list
Write your own parser !
#!/usr/bin/env python
import sys
def handle_args(args):
s = False
for a in args:
if a == '-s':
if s:
break
else:
s = True
else:
yield (s, a)
s = False
if s:
raise RuntimeError('missing argument for -s')
for item in handle_args(sys.argv[1:]):
print(item)
'''my output --->
(False, 'firstargument')
(False, 'secondargument')
(True, 'thirdargument')
(True, 'fourth')
(False, 'fifth')
(True, 'sixth')
'''
Again, tailles_entry is a single ttk.Entry instance at line 29, then what does tailles_entry[i] mean ? You should probably create a list of entries.
Hello!
There are inconsistencies in your variable's types. For exemple in the code above, at line 24, qtaillevar is a StringVar, but at line 26, it is a dictionary. In the same way tailles_entry is a ttk.Entry at line 36, but it is used elsewhere with a subscript [i] like a list. You should decide which is the type of each variable and check that every expression where this variable appears uses the variable according to this type.
Try print 'elapsed: %.2f seconds' % elapsed.total_seconds()
You can use datetime
>>> import datetime as dt
>>>
>>> start = dt.datetime.now()
>>> start
datetime.datetime(2013, 7, 16, 0, 21, 17, 748591)
>>> # drink some cofee
...
>>> death_date = dt.datetime.now()
>>> elapsed = death_date - start
>>> elapsed
datetime.timedelta(0, 81, 872052)
>>> elapsed.total_seconds()
81.872052
in qtetaillevar[i] = tailles_entry[i].get()
, you could check that tailles_entry is a list. Your error message suggests that it is a tkinter type. Try
print(type(tailles_entry))
item = tailles_entry[i]
print(type(item))
qtetaillevar[i] = item.cget()
Hello ,
Thank you very much Gribouillis , when i used modelidvar.get() , it could print "liste1" at line 46 ,
but couldn't execute the instruction at line 59 , the error i got is : TypeError: cannot concatenate 'str' and 'int' objects
Can you post the full traceback ? It seems unlikely that the error comes from line 59.
What I don't like in the code is your use of global variables everywhere. It is likely to generate cryptic errors. Write a class
class Glo:
pass
glo = Glo()
then use glo.distligne
, etc instead of global variables and remove all global statements.
I think PY_VAR4 is the TCL name of your StringVar. Try to use modelidvar.get()
at line 46. Also the % operator is not the prefered way to substitute values in SQL statements.
You can try
hr, sc = divmod(counter, 3600)
mn, sc = divmod(sc, 60)
msg = '%d hours, %d minutes and %d seconds' % (hr, mn, sc)
print(msg)
I don't understand, it works very well:
>>> import random
>>> notdone = [tuple((x,y))for x in range(5) for y in range(6)]
>>> from functools import partial
>>> s = partial(random.choice, notdone)
>>> a = s()
>>> print(a)
(0, 5)
>>> notdone.remove(a)
>>>
Notice that my code prints (0, 5)
and not ((0, 5),)
.
random.sample()
returns a list. Try this
notdone = [tuple((x,y))for x in range(5) for y in range(6)]
from functools import partial
s = partial(random.choice, notdone)
You can try to sort the words by decreasing length in the regex
L = sorted(Dic_Word, key = len, reverse = True)
rc = re.compile('|'.join(map(re.escape, L)))
Please why I get this error when I run my code?
Don't call your file crypt.py if it is importing a module named crypt. Remove any file crypt.py or crypt.pyc from your folder.
Upgrade to linux !
I'm trying to make the code general as possible so that any csv file and column index can be used.
There is some work if you want to reach this universality. Csv files may vary on their encoding, their quoting strategy, their separator. See the csv module's documentation, especially the part about dialects and the discussion about unicode.
The most obvious possible error in your code is if column_index is larger than the length of a line. You will get an IndexError!
Use the Command class in this code snippet to get your shell command's output
com = Command(zip_command).run()
print(com.output)
print(com.error)
if com.failed:
print('BACKUP FAILED!')
else:
print('Successful backup to ' + target)
os.system()
is deprecated in favor of the subprocess
module.
You may also consider using module zipfile
instead of an external command.
Use dictionaries
D = [dict(zip(*WordsFrequencies(name))) for name in ['file1.txt', 'file2.txt']]
common_words = set(D[0]) & set(D[1])
L = [(w, D[0][w] + D[1][w]) for w in common_words]
# sort by decreasing frequencies, solve ties by increasing alphabetical order.
L.sort(key = lambda t: (-t[1], t[0]))
L = L[:20]
Always post the traceback when you report such errors! If it is a SyntaxError, use print("module {0}".format(key))
. Otherwise, the format() method could cause an error in some cases (unicode encoding, or use of a custom class).
Then try subprocess.Popen("open /Applications/Snes9x.app", shell=True)
When I said a terminal, I did not mean a python shell, but an OS terminal or console. What happens when you type
/Applications/Snes9x.app
in a console ?
With shell = False
, the first argument must be a list:
subprocess.Popen(['/Applications/Snes9x.app',], shell=False)
Would that be the same case with the output "/Applications/Snes9x.app: is a directory?"
It means that /Applications/Snes9x.app
is a directory. Popen expects an executable program. Try the command in a terminal first. If it works in a terminal, it should work in python with Popen.
Permission denied means that the user who is running your python program doesn't have the permission to list the directory, or to run Snes9x, or that Snes9x is not an executable program, etc. It is a system issue, not a python issue.
Use the subprocess module
process = subprocess.Popen('Snes9x', shell = True)
Use len(list(combinations(numbers, 6)))
There is no problem in jumping back and forth if you do it through class instances, for example in module A
# mod A
from B import foo
class Bar(object):
def baz(self):
print("qux")
x = Bar()
foo(x) # call function foo from module B
and in module B
# mod B
def foo(bar):
bar.baz() # call method .baz() defined in module A
Notice that module B uses module A features without importing anything from A.
The best solution to avoid circular imports. If A imports B, then B should not import A, or import from A (although python is very permissive and will tolerate almost everything). Here, main imports submodule and both use printa(). You can write printa() and num_values in a third module, and import thirdmod in both main and submodule.
The first way is to define __getattr__()
class Bar(object):
def __getattr__(self, attr):
return getattr(self.foo, attr)
You can add some conditions on attr to avoid unexpected calls
class Bar(object):
def __getattr__(self, attr):
if some_condition(attr):
return getattr(self.foo, attr)
else:
raise AttributeError(attr)
Another way is to define methods by a loop, eg
class Bar(object):
for name in "meth_a meth_b meth_c".split():
exec "def {name}(self, *args, **kwd): return self.foo.{name}(*args, **kwd)".format(name=name)
del name
There are other ways, you could write a function which inserts methods in class Bar, etc
is there a way for the python code to stop if they pick the wrong answer?
You can exit your program at any time with
import sys
sys.exit(0)
The value 0 means to the OS that your program executed normally. You may exit with another value to indicate an error.
At line 8, python thinks that a variable left
is used, which was not previously defined. You probably meant
if partone == 'left':
Here 'left'
is a constant string instead of a variable name.
I also want to remove header line (first line) and want to catenate rest of the lines.
This code removes the first line of a file and prints the rest, concatenated
whith open("myfile.txt", "rb") as ifh:
next(ifh) # skip first line
print(''.join(x.rstrip('\n') for x in ifh)) # read the rest, concatenate and print
Use the format method
#!/usr/bin/env python
# -*-coding: utf8-*-
from __future__ import unicode_literals, print_function, division
template = str("""<Result Type="PkFilter" Name="{RowNum:0>2d}"
Color="{Color}" Show="0" MinIntensity="0"
IntensityThreshold="100" AbsIntens="0"
LogScale="0" MinMass="{MinMass}"
MaxMass="{MaxMass}" Integrate="1"
UsePercentile="0"
IntensityPercentile="0.95"
FindMass="0" RelMass="1"></Result>""").replace("\n", " ")
def result(RowNum, MinMass, MaxMass, Color=str("#0000ff")):
return template.format(
RowNum = int(RowNum),
MinMass = repr(float(MinMass)), # repr instead of str to keep floating precision
MaxMass = repr(float(MaxMass)),
Color = Color,
)
if __name__ == "__main__":
print(result(5, 3.14, 31.4))
Can i reference this dict within the class ?
Sure, in this case mac_address
is a global variable, which can be accessed from any function's body in the same file, including class methods.
There is no best way, there are different ways
>>> class A(object):
... def __init__(self):
... self.mydict = dict() # <-- a dict is added to every instance
...
>>> a = A()
>>> a.mydict["foo"] = "bar"
>>>
>>> class B(object):
... shareddict = dict() # <-- this dict can be used by all instances
... def __init__(self):
... pass
...
>>> b = B()
>>> b.shareddict["foo"] = "bar"
>>> b2 = B()
>>> b2.shareddict
{'foo': 'bar'}
>>>
>>> class C(object):
... pass
...
>>> c = C()
>>> c.__dict__ # <-- instances usually have a predefined dict to store attributes
{}