w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » PYTHON » Page 4
How do you get Python to open a text file using print and input? I have the code I am using below
Python 3.x filename = input("What is the text file's name?") with open(filename) as f: for line in f: print(line) Python 2.x filename = raw_input("What is the text file's name?") with open(filename) as f: for line in f: print line Note that you may either use: A file name if the file is in the current working directory, e.g. data.txt A relative path from you

Categories : Python

Printing a list to a Tkinter Text widget
Append newline (' ') manually: from Tkinter import * # from tkinter import * lst = ['a', 'b', 'c', 'd'] root = Tk() t = Text(root) for x in lst: t.insert(END, x + ' ') t.pack() root.mainloop() BTW, you don't need to use index to iterate a list. Just iterate the list. And don't use list as a variable name. It shadows builtin function/type list.

Categories : Python

Multiple updating plot with pyqtgraph in Python
One problem is that you are appending to lists. This gets to be very slow when the lists grow large, as Python has to copy the full list to a new location that is one cell larger than the previous one. You could test this by running your code again with the appends removed, but continuing to read the data (which you throw away for that test). If that is the problem, there are several solutions:

Categories : Python

SyntaxError when running with Python 2
It appears that your script controlled_biomass_exp.py overwrites run in your current namespace. This toy example will produce a similar problem: # file: test.py run = "hello world!" print(run) Calling run in IPython is just a shortcut for %run which is a built-in magic function. Once you overwrite run (e.g. as shown in my toy example) you cannot use the shortcut anymore. However, %run control

Categories : Python

GUI not updating when adding a call to an external EM simulation program
I would imagine that you are interrupting the mainloop whilst running your simulation. If you want to do both at the same time, you may need to look into making your program multi threaded so that both the mainloop and your simulation can run concurrently.

Categories : Python

Websocket connection with autobahn and twisted in python
reactor.connectTCP accepts as its first argument an IP address (or a hostname). You passed it a URI. It got confused and decided this must be a hostname, tried to resolve it, failed, and stopped the client factory. Try passing real.okcoin.com instead of the full URI. This can be resolved to an IP address (I assume) and the connection attempt will be able to proceed further.

Categories : Python

How can I create an Exception in Python minus the last stack frame?
You can get the current frame and any other level using the inspect module. For instance, here is what I use when I'd like to know where I'm in my code : from inspect import currentframe def get_c_frame(level = 0) : """ Return caller's frame """ return currentframe(level) ... def locate_error(level = 0) : """ Return a string containing the filename, function name and lin

Categories : Python

Writing to csv error handling
The first obvious thing to do would be to check the HTTP status code for the response object. It's not an explicit part of the Google API documentation but obviously something else than a 200 ("Found") HTTP status code means you have a problem and you cannot even expect to get anything useful in the response's body. HTTP response codes are documented in the HTTP RFC. Then if you read the API's d

Categories : Python

Beautfiul Soup 3: convert two-byte Unicode sequences to actual Unicode characters
The characters you are looking at look like double-encoded UTF-8. If the input is hosed, there really isn't anything BeautifulSoup can do to rectify it. BeautifulSoup basically returns Unicode always, which is just as it should be (unless you are actually into manipulating encodings, in which case it's a hopeless hassle). It is possible, though unlikely, that BeautifulSoup is the source for the

Categories : Python

Error in Recursion
Your function Reduce() is not returning anything when it recurses. You'd want to change def Reduce(n) : if Check_Prime(n) : Reduce(n-1) else : return n into def Reduce(n) : if Check_Prime(n) : return Reduce(n-1) else : return n That way, each code path in Reduce returns a value.

Categories : Python

Joining the numbers to form a new number
Use str.join with for loop l = [1, 2, 3] In [75]: int(''.join(str(i) for i in l)) Out[75]: 235 Or use simple math:- In [77]: s = 0 In [78]: for x in l: ....: s = s*10 + x ....: In [79]: s Out[79]: 235

Categories : Python

BeautifulSoup splitting scrapped string into three rows
You could do simply like in the below example, In [23]: from bs4 import BeautifulSoup In [24]: s = """<td>1</td> ...: <td>2</td> ...: <td>3</td> ...: <td>4</td> ...: <td>5</td> ...: <td>6</td>""" In [4]: soup = BeautifulSoup(s) In [25]: td = [i.string for i in soup.find_all("td")] In [26]: td Out[26]:

Categories : Python

Python conditional block within try block
There is nothing wrong with your code. As @Tomo said, you can use any code within the try block. You said: I have run the test where module1 cannot be imported and the file module2.py exists This means permissions are not granted to perform os.stat() on your file module2.py. So all what you have to do is to chmod your file with the needed permissions (you can chmod it in 777 as a first test

Categories : Python

Twisted Could not accept new connection (EMFILE)
You are running out of available file descriptors, either on a per-user, per-process or per-computer basis. You may need to change some ulimit or sysctl parameters to increase these limits. Depending on your operating system this may be slightly different. For example, here's the relevant chapter of the FreeBSD handbook about tuning limits with sysctl.

Categories : Python

Multi-threading with Class and without class in python using join
target should be a function, not the result of a function (unless that result is a function). eg. target=printer. Note the absence of brackets. What you have effectively done is run printer three times. Then started three threads which have nothing to do. Then printed bye bye.

Categories : Python

Where to find the file after uploading via Flask/Python/Heroku?
The file is at filename = secure_filename(file.filename) file.save(os.path.join("/tmp/", filename)) which means whatever filename is, in the /tmp/ directory. No. It should be in /tmp/ filename. Although I don't think this is a valid location for heroku. I suspect you have to upload content to someplace else, like Amazon S3 or direct via node. The online location, such as S3 will have a

Categories : Python

Hashed password authentication in Python not working
linecache.getline returns ' ' character. https://docs.python.org/2/library/linecache.html This code should work: salt = linecache.getline(userin + '.userdat', 2).strip() saltin = newin + salt hashed_newin = (hashlib.sha256(saltin.encode()).hexdigest()) realin = linecache.getline('file.dat', 1).strip() if hashed_newin == realin: return True

Categories : Python

Join unicode u with non-ASCII value in python
The prefix only works for literal values; the syntax with prefix creates a different object type from the syntax without. To convert already created str objects, you need to decode them to Unicode, and in the other direction unicode objects can be converted to str objects by encoding them to bytes. If you don't explicitly decode bytes to Unicode, Python does this for you, implicitly, with the AS

Categories : Python

cv.COLOR_BGR2LAB gives wrong range
You are correct, the LAB values returned from OpenCV will never lie outside the range 0-100, 0-255, 0-255. But: the LAB color space's gamut exceeds the one of RGB color spaces, see for example the second paragraph in the wikipedia article on LAB. Thus, when you convert from RGB/BGR to LAB, you will never get the full LAB range, as LAB contains colors that can't be represented in RGB.

Categories : Python

Dataframe from multiple json files in R or Python
Here's one way, using the fromJSON offered in the jsonlite package: do.call(rbind, lapply(readLines('mydata.json'), jsonlite::fromJSON)) # num name link # 1 1 Swab Summer: Transformation At the United

Categories : Python

Pylab plot shows no plot points
It appears you want to plot one point at the time. Don't do that: collect all the data into an array (from the logfile), then plot that all at once. So, do all the plotting outside your for loop: import matplotlib.pylab as pylab logfile = file('sensorlog.txt','r') pylab.figure(1) pylab.xlabel('Time Steps') pylab.ylabel('Fan Temperature') temperatures = [] for line in logfile: if line[0].isdi

Categories : Python

Python: Run windows CMD commands through python, using å,ä and ö
I could do some tests on a windows 7 system. The problem is not on the execution of a command but only on the display of UTF-8 characters. First, it works almost correctly using Python 3.4 : it can display ä without problems. So I assume you are using a 2.x version. On a 2.x version, it is almost impossible to have proper display of UTF8 strings. If you manage to do it correctly, the driver wil

Categories : Python

Selenium phantomjs does not work for twitter.com
PhantomJS 1.9.8 does the work for twitter. New version available here: http://phantomjs.org/download.html Previously I used the older version of the PhantomJS: 1.9.7.

Categories : Python

python etree with xpath and namespaces with prefix
Oh, I found it. After we do that: dom = ET.parse(u'C:\filepath\1.xml') rootxml = dom.getroot() Object rootxml contains dictionary nsmap, which contains all namespaces that I want. So, simplest solution I've found: dom = ET.parse(u'C:\filepath\1.xml') rootxml = dom.getroot() nss = rootxml.nsmap for subtag in rootxml.xpath(u'//par:actual', namespaces=nss): #do something print(subtag)

Categories : Python

MongoEngine: storing EmbeddedDocument in DictField
I finally found the answer to my problem. The correct way to achieve this pattern is by making use of a MapField. The corresponding model in MongoEngine looks like: class Inner(EmbeddedDocument): name = StringField() class Outer(Document): outer_data = StringField() embed = MapField(EmbeddedDocumentField(Inner)) In MongoDB, all keys needs to be strings so there is no need to specify a "

Categories : Python

Why does the value of a variable changes on appending to python list as a list?
The number stored is the same in both cases. The only difference is what is being printed. Consider this: >>> a=1.234567890123456789 >>> print a 1.23456789012 >>> print [a] [1.2345678901234567] In the first case, the equivalent of str(a) is invoked, which does not show the full precision. In the second case, repr(a) is used.

Categories : Python

Numpy sum every n columns of matrix
Here's one way; first reshape x to a 3D array and then sum over the last axis: >>> x.reshape(-1, 4, 3).sum(axis=2) array([[ 3, 12, 21, 30], [ 3, 12, 21, 30], [ 3, 12, 21, 30], [ 3, 12, 21, 30], [ 3, 12, 21, 30], [ 3, 12, 21, 30], [ 3, 12, 21, 30], [ 3, 12, 21, 30], [ 3, 12, 21, 30], [ 3, 12, 21, 30]])

Categories : Python

How to increase paramiko performance
You can check the exit status of the command - no need to use time.sleep. One possible solution: first, define a function to connect to the ssh server: def createSSHClient(server, port, user, password): client = paramiko.SSHClient() client.load_system_host_keys() client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) client.connect(server, port, user, password) return c

Categories : Python

python doc to docx conversion, comtypes.Documents.Open throwing ValueError: NULL COM pointer access
If you are still having this issue, this is what helped me for exactly the same layout of AWS(Win2012)-Apache(64bit)-Django: Change the DCOM Config Settings: Start -> dcomcnfg.exe Computers -> My Computer DCOM Config Select the Microsoft Word 97-2003 Documents -> Properties Tab Identity, change from Launching User to Interactive User

Categories : Python

cursor.execute in python for SQL
Explicitly cast the LOGINPROPERTY return value to an integer to work around the data type mapping problem by changing the query from this: "select loginproperty('tibbr_db','DaysUntilExpiration')" to this: "select cast(loginproperty('tibbr_db','DaysUntilExpiration') as integer)" The DaysUntilExpiration property in SQL Server should always return an integer, so you won't see any type errors wi

Categories : Python

Instancing a Table from __tablename__ in SQLAlchemy
Create_a.py import os import sys from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class A(Base): __tablename__ = 'X' A_id = Column(Integer, primary_key=True) A_name = Column(String(250), nullable=False) engine = cre

Categories : Python

What are the best ways to have a python program and c program share data
I would consider using nanomsg for this. http://nanomsg.org/ It's a simple-to use C-only IPC library, with good python bindings also available. Alternatively, use it's older, but also awesome ZeroMQ if you like. Last but not least, while multiprocess-approaches are a good thing (tm), you could consider using ctypes and build a python wrapper around it. The advantage of this approach is that yo

Categories : Python

Numpy: Extract particular rows in matrix
If you are willing to use a list comprehension to generate the indexes, then you can use: w[np.array([np.arange(i,j) for i,j in np.hstack((y1,y2))]).ravel()] If you really can't use loops, try: a = np.hstack((y1,y2)) func = lambda i: np.arange(a[i][0],a[i][1]) b = np.vectorize(func,otypes=[np.ndarray]) w[np.hstack(b(np.arange(4)))]

Categories : Python

Django-taggit adding new tags to an object?
django-taggit does exactly what you want, but in your case sampletag != Sample_tag so another Tag instnace is created. >>> i.tags.all() [] >>> i.tags.add("test") >>> i.tags.all() [<Tag: test>] >>> i.tags.add("test") >>> i.tags.all() [<Tag: test>] >>>

Categories : Python

Trying to use the Pillow library to create a gif‏
I guess this is the problem: s = list(s) You may think that s is global variable, but for python s is local variable, due to assignment. To make s global do: def main(im): global s ... Also you are catching all exceptions, so probably you are not getting any errors. If you really insist on the catching just do the following for now: except Exception as inst: raise(inst) This s

Categories : Python

Rails app to work with a remote heroku database
I don't see any problem in doing this, as far as rails manages the database structure and python script populates it with data. My advice, but just to make it simpler, is to define the database schema through migrations in your rails app and build it like the python script doesn't exist. Once you have completed it, simply start the python script so it can start populating the Database (could be ne

Categories : Python

Python: No Traceback when Scraping Data into Excel Spreadsheet
If there is no traceback then there is no error. Most likely something has gone wrong with your scraping/parsing code and your raw_list or other arrays aren't populated. Try print out the data that should be written to the worksheet in the last loop to see if there is any data to be written. If you aren't writing data to the worksheet then it will be empty.

Categories : Python

if not line.startswith - give to much single quotes and line bracks
Simply change your code like below. You don't need to go for a replace function. for r in log: host_line = "'",r['host'],"'" for line in host_line: if not line.startswith("178.255.20.20"): if not line == "'": print line.strip()

Categories : Python

element tree parse xml text string to be called by eval
You probably shouldn't use eval... But to answer your question on how to store an object to be later executed but eval, you do repr(my_object), this will often return a string, suitable for eval, but this is not always true.

Categories : Python




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.