text stringlengths 185 26.5k |
|---|
<s>[INST] How to calculate the angle between a line and the horizontal axis? In a programming language (Python, C#, etc) I need to determine how to calculate the angle between a line and the horizontal axis?
I think an image describes best what I want:
Given (P1x,P1y) and (P2x,P2y) what is the best way to calculate th... |
<s>[INST] Convert list to tuple in Python I'm trying to convert a list to a tuple.
When I google it, I find a lot of answers similar to:
l = [4,5,6]
tuple(l)
But if I do that I get this error message:
TypeError: 'tuple' object is not callable
How can I fix this problem?
[/INST] It should work fine. Don't use tuple... |
<s>[INST] No module named MySQLdb I am using Python version 2.5.4 and install MySQL version 5.0 and Django. Django is working fine with Python, but not MySQL. Can anyone help me to solve this issue? I am using it in Vista.
[/INST] You need to use one of the following commands. Which one depends on what OS and software... |
<s>[INST] Python "extend" for a dictionary Which is the best way to extend a dictionary with another one? For instance:
>>> a = { "a" : 1, "b" : 2 }
>>> b = { "c" : 3, "d" : 4 }
>>> a
{'a': 1, 'b': 2}
>>> b
{'c': 3, 'd': 4}
I'm looking for any operation to obtain this avoiding for loop:
{ "a" : 1, "b" : 2, "c" : 3, "d... |
<s>[INST] How to convert strings into integers in Python? I have a tuple of tuples from a MySQL query like this:
T1 = (('13', '17', '18', '21', '32'),
('07', '11', '13', '14', '28'),
('01', '05', '06', '08', '15', '16'))
I'd like to convert all the string elements into integers and put it back nicely to li... |
<s>[INST] How do I sort a list of strings in Python? What is the best way of creating an alphabetically sorted list in Python?
[/INST] Basic answer:
mylist = ["b", "C", "A"]
mylist.sort()
This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the s... |
<s>[INST] Chain-calling parent constructors in python Consider this - a base class A, class B inheriting from A, class C inheriting from B. What is a generic way to call a parent class constructor in a constructor? If this still sounds too vague, here's some code.
class A(object):
def __init__(self):
print ... |
<s>[INST] Python: Find in list I have come across this delightful:
item = someSortOfSelection()
if item in myList:
doMySpecialFunction(item)
but sometimes it does not work with all my items, as if they weren't recognized in the list (when it's a list of string).
is it the most 'pythonic' way of finding an item in ... |
<s>[INST] Difference between __getattr__ vs __getattribute__ I am trying to understand when to use __getattr__ or __getattribute__. The documentation mentions __getattribute__ applies to new-style classes. What are new-style classes?
[/INST] A key difference between __getattr__ and __getattribute__ is that __getatt... |
<s>[INST] C-like structures in Python Is there a way to conveniently define a C-like structure in Python? I'm tired of writing stuff like:
class MyStruct():
def __init__(self, field1, field2, field3):
self.field1 = field1
self.field2 = field2
self.field3 = field3
[/INST] Use a named tuple,... |
<s>[INST] Separation of business logic and data access in django I am writing a project in Django and I see that 80% of the code is in the file models.py. This code is confusing and, after a certain time, I cease to understand what is really happening.
Here is what bothers me:
I find it ugly that my model level (which... |
<s>[INST] What is a monkey patch? I am trying to understand, what is a monkey patch?
Is that something like methods/operators overloading or delegating?
Does it have anything common with these things?
[/INST] No, it's not like any of those things. It's simply the dynamic replacement of attributes at runtime.
For ins... |
<s>[INST] Tabs versus spaces in Python programming I have always used tabs for indentation when I do Python programming. But then I came across a question here on SO where someone pointed out that most Python programmers use spaces instead of tabs to minimize editor-to-editor mistakes.
How does that make a difference? ... |
<s>[INST] What do the python file extensions, .pyc .pyd .pyo stand for? What do these python file extensions mean?
.pyc
.pyd
.pyo
What are the differences between them and how are they generated from a *.py file?
[/INST]
.py: This is normally the input source code that you've written.
.pyc: This is the compiled byt... |
<s>[INST] Can I use Python as a Bash replacement? I currently do my textfile manipulation through a bunch of badly remembered AWK, sed, Bash and a tiny bit of Perl.
I've seen mentioned a few places that python is good for this kind of thing, I know a little and I would like to know more. Is Python a good choice for thi... |
<s>[INST] How do I execute a program from python? os.system fails due to spaces in path I have a python script that needs to execute an external program, but for some reason fails.
If I have the following script:
import os;
os.system("C:\\Temp\\a b c\\Notepad.exe");
raw_input();
Then it fails with the following error:... |
<s>[INST] Adding new column to existing DataFrame in Python pandas I have a DataFrame with named columns and rows indexed with not- continuous numbers like from the code:
df1 = DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])
mask = df1.applymap(lambda x: x <-0.7)
df1 = df1[-mask.any(axis=1)]
sLength = l... |
<s>[INST] Why do some functions have underscores "__" before and after the function name? This seems to occur a lot, and was wondering if this was a requirement in the Python language, or merely a matter of convention?
Also, could someone name and explain which functions tend to have the underscores, and why (__init__,... |
<s>[INST] How do I fix 'ImportError: cannot import name IncompleteRead'? When I try to install anything with pip or pip3, I get:
$ sudo pip3 install python3-tk
Traceback (most recent call last):
File "/usr/bin/pip3", line 9, in <module>
load_entry_point('pip==1.5.6', 'console_scripts', 'pip3')()
File "/usr/lib/... |
<s>[INST] How can I parse a YAML file in Python How can I parse a YAML file in Python?
[/INST] The easiest and pureist method without relying on C headers is PyYaml:
#!/usr/bin/env python
import yaml
with open("example.yaml", 'r') as stream:
try:
print(yaml.load(stream))
except yaml.YAMLError as exc:... |
<s>[INST] How to avoid .pyc files? Can I run the python interpreter without generating the compiled .pyc files?
[/INST] From "Whatâs New in Python 2.6 - Interpreter Changes":
Python can now be prevented from
writing .pyc or .pyo files by
supplying the -B switch to the Python
interpreter, or by setting the
P... |
<s>[INST] What does the at (@) symbol do in Python I'm looking at some Python code which used the @ symbol, but I have no idea what it does. I also do not know what to search for as searching python docs or Google does not return relevant results when the @ symbol is included.
[/INST] Preamble
I admit it took more tha... |
<s>[INST] Typical Angular.js workflow and project structure (with Python Flask) I am pretty new to this whole MV* client-side framework frenzy. It doesn't have to be Angular.js, but I picked it because it feels more natural to me than either Knockout, Ember or Backbone. Anyway what is the workflow like? Do people start... |
<s>[INST] Should Python import statements always be at the top of a module? PEP 08 states:
Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.
However if the class/method/function that I am importing is only used in rare cases, surely ... |
<s>[INST] Pythonic way to avoid "if x: return x" statements I have a method that calls 4 other methods in sequence to check for specific conditions, and returns immediately (not checking the following ones) whenever one returns something Truthy.
def check_all_conditions():
x = check_size()
if x:
return ... |
<s>[INST] Get unique values from a list in python I want to get the unique values from the following list:
[u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']
The output which I require is:
[u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow']
I tried the following code:
output = []
f... |
<s>[INST] How can I fill out a Python string with spaces? I want to fill out a string with spaces. I know that the following works for zero's:
>>> print "'%06d'"%4
'000004'
But what should I do when I want this?:
'hi '
of course I can measure string length and do str+" "*leftover, but I'd like the shortest way.
... |
<s>[INST] How to set the current working directory in Python? How to set the current working directory in Python?
[/INST] Try os.chdir
os.chdir(path)
        Change the current working directory to path. Availability: Unix, Windows.
</s> |
<s>[INST] Can I get JSON to load into an OrderedDict in Python? Ok so I can use an OrderedDict in json.dump. That is, an OrderedDict can be used as an input to JSON.
But can it be used as an output? If so how? In my case I'd like to load into an OrderedDict so I can keep the order of the keys in the file.
If not, is th... |
<s>[INST] TypeError: 'str' does not support the buffer interface plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wb") as outfile:
outfile.write(plaintext)
The above python code is giving me following error:
Tra... |
<s>[INST] Understanding dict.copy() - shallow or deep? While reading up the documentation for dict.copy(), it says that it makes a shallow copy of the dictionary. Same goes for the book I am following (Beazley's Python Reference), which says:
The m.copy() method makes a shallow
copy of the items contained in a
ma... |
<s>[INST] mysql_config not found when installing mysqldb python interface I am trying to get a Python script to run on the linux server I'm connected to via ssh. The script uses mysqldb. I have all the other components I need, but when I try to install mySQLdb via setuptools like so:,
python setup.py install
I get th... |
<s>[INST] How to make an unaware datetime timezone aware in python What I need to do
I have a timezone-unaware datetime object, to which I need to add a time zone in order to be able to compare it with other timezone-aware datetime objects. I do not want to convert my entire application to timezone unaware for this on... |
<s>[INST] How to Python prettyprint a JSON file I have a JSON file that is a mess that I want to prettyprint-- what's the easiest way to do this in python? I know PrettyPrint takes an "object", which I think can be a file, but I don't know how to pass a file in-- just using the filename doesn't work.
[/INST] The json ... |
<s>[INST] How to get the position of a character in Python? How can I get the position of a character inside a string in python?
[/INST] There are two string methods for this, find and index.
Example:
>>> myString = "Position of a character"
>>> myString.index('s')
2
The difference is that find returns -1 when what y... |
<s>[INST] Django - How to rename a model field using South? I would like to change a name of specific fields in a model:
class Foo(models.Model):
name = models.CharField()
rel = models.ForeignKey(Bar)
should change to:
class Foo(models.Model):
full_name = models.CharField()
odd_relation = models.... |
<s>[INST] Reading binary file in Python and looping over each byte In Python, how do I read in a binary file and loop over each byte of that file?
[/INST] f = open("myfile", "rb")
try:
byte = f.read(1)
while byte != "":
# Do stuff with byte.
byte = f.read(1)
finally:
f.close()
By suggestio... |
<s>[INST] How to declare an array in Python? How do I declare an array in Python?
I can't find any reference to arrays in the documentation.
[/INST] variable = []
Now variable refers to an empty list*.
Of course this is an assignment, not a declaration. There's no way to say in Python "this variable should never ref... |
<s>[INST] Using module 'subprocess' with timeout Here's the Python code to run an arbitrary command returning its stdout data, or raise an exception on non-zero exit codes:
proc = subprocess.Popen(
cmd,
stderr=subprocess.STDOUT, # Merge stdout and stderr
stdout=subprocess.PIPE,
shell=True)
communicate... |
<s>[INST] pip install lxml error this is my error :
(mysite)zjm1126@zjm1126-G41MT-S2:~/zjm_test/mysite$ pip install lxml
Downloading/unpacking lxml
Running setup.py egg_info for package lxml
Building lxml version 2.3.
Building without Cython.
ERROR: /bin/sh: xslt-config: not found
** make sure the d... |
<s>[INST] Importing modules from parent folder I am running Python 2.5.
This is my folder tree:
ptdraft/
nib.py
simulations/
life/
life.py
(I also have __init__.py in each folder, omitted here for readability)
How do I import the nib module from inside the life module? I am hoping it is possible to do wi... |
<s>[INST] pip install from github repo branch Seems to be rather straightforward but I just can't get it right. Trying to pip install a repo's specific branch. Googling tells me to
pip install https://github.com/user/repo.git@branch
The branch's name is issue/34/oscar-0.6 so I did pip install https://github.com/ta... |
<s>[INST] Circular (or cyclic) imports in Python What will happen if two modules import each other?
To generalize the problem, what about the cyclic imports in Python?
[/INST] There was a really good discussion on this over at comp.lang.python last year. It answers your question pretty thoroughly.
Imports are pretty ... |
<s>[INST] How do I watch a file for changes using Python? I have a log file being written by another process which I want to watch for changes. Each time a change occurrs I'd like to read the new data in to do some processing on it.
What's the best way to do this? I was hoping there'd be some sort of hook from the PyWi... |
<s>[INST] How do I resize an image using PIL and maintain its aspect ratio? Is there an obvious way to do this that I'm missing? I'm just trying to make thumbnails.
[/INST] Define a maximum size.
Then, compute a resize ratio by taking min(maxwidth/width, maxheight/height).
The proper size is oldsize*ratio.
There is o... |
<s>[INST] What does the Python Ellipsis object do? While idly surfing the namespace I noticed an odd looking object called "Ellipsis", it does not seem to be or do anything special, but it's a globally available builtin.
After a search I found that it is used in some obscure variant of the slicing syntax by Numpy and ... |
<s>[INST] Python access to first element in dictionary If dict is not empty, the way I use to access first element in dict is:
dict[dict.keys()[0]]
Is there any better way to do this?
[/INST] Non-destructively you can:
dict.itervalues().next()
On Python 3 this becomes
next (iter (dict.values()))
If you want it to w... |
<s>[INST] Python List vs. Array - when to use? If you are creating a 1d array, you can implement it as a List, or else use the 'array' module in the standard library. I have always used Lists for 1d arrays.
What is the reason or circumstance where I would want to use the array module instead?
Is it for performance and... |
<s>[INST] How to find out if a Python object is a string? How can I check if a Python object is a string (either regular or Unicode)?
[/INST] Python 2
Use isinstance(obj, basestring) for an object-to-test obj.
Docs.
</s> |
<s>[INST] How do I disable log messages from the Requests library? By default, the Requests library writes log messages to the console, along the lines of Starting new HTTP connection (1): example.com etc. I'm usually not interested in these messages, how do I disable them?
[/INST] I found out how to configure request... |
<s>[INST] Why is "except: pass" a bad programming practice? I often see comments on other Stack Overflow questions about how the use of except: pass is discouraged. Why is this bad? Sometimes I just don't care what the errors, are and I want to just continue with the code.
try:
something
except:
pass
Why is us... |
<s>[INST] Why doesn't Python have multiline comments? OK, I'm aware that triple-quotes strings can serve as multiline comments. For example,
"""Hello, I am a
multiline comment"""
and
'''Hello, I am a
multiline comment'''
But technically speaking these are strings, correct?
I've googled and read the Python st... |
<s>[INST] Install a Python package into a different directory using pip? I know the obvious answer is to use virtualenv and virtualenvwrapper, but for various reasons I can't/don't want to do that.
So how do I modify the command
pip install package_name
to make pip install the package somewhere other than the default ... |
<s>[INST] What are Class methods in Python for? I'm teaching myself Python and my most recent lesson was that Python is not Java, and so I've just spent a while turning all my Class methods into functions.
I now realise that I don't need to use Class methods for what I would done with static methods in Java, but now I'... |
<s>[INST] How can I check for Python version in a program that uses new language features? If I have a Python script that requires at least a particular
version of Python, what is the correct way to fail gracefully
when an earlier version of Python is used to launch the script?
How do I get control early enough to issu... |
<s>[INST] How do I calculate number of days betwen two dates using Python? If I have two dates (ex. '8/18/2008' and '9/26/2008') what is the best way to get the difference measured in days?
[/INST] If you have two date objects, you can just subtract them.
from datetime import date
d0 = date(2008, 8, 18)
d1 = date(200... |
<s>[INST] How can I install packages in my $HOME folder with pip? Is it possible? When installing pip, install the python packages inside my $HOME folder. (for example, I want to install mercurial, using pip, but inside $HOME instead of /usr/local)
I'm with a mac machine and just thought about this possibility, instead... |
<s>[INST] Is there any difference between "foo is None" and "foo == None"? Is there any difference between:
if foo is None: pass
and
if foo == None: pass
The convention that I've seen in most Python code (and the code I myself write) is the former, but I recently came across code which uses the latter. None is an in... |
<s>[INST] Understanding __get__ and __set__ and Python descriptors I am trying to understand what Python's descriptors are and what they can useful for. However, I am failing at it. I understand how they work, but here are my doubts. Consider the following code:
class Celsius(object):
def __init__(self, value=0.0):... |
<s>[INST] Reloading submodules in IPython Currently I am working on a python project that contains sub modules and uses numpy/scipy. Ipython is used as interactive console. Unfortunately I am not very happy with workflow that I am using right now, I would appreciate some advice.
In IPython, the framework is loaded by a... |
<s>[INST] Class method differences in Python: bound, unbound and static What is the difference between the following class methods?
Is it that one is static and the other is not?
class Test(object):
def method_one(self):
print "Called method_one"
def method_two():
print "Called method_two"
a_test = Test()... |
<s>[INST] How do I test one variable against multiple values? I'm trying to make a function that will compare multiple variables to an integer and output a string of three letters. I was wondering if there was a way to translate this into Python. So say:
x = 0
y = 1
z = 3
Mylist = []
if x or y or z == 0 :
Mylist.a... |
<s>[INST] Asking the user for input until they give a valid response I am writing a program that must accept input from the user.
#note: Python 2.7 users should use `raw_input`, the equivalent of 3.X's `input`
age = int(input("Please enter your age: "))
if age >= 18:
print("You are able to vote in the United State... |
<s>[INST] Is there a Numpy function to return the first index of something in an array? I know there is a method for python list to return the first index of something
l = list(1,2,3)
l.index(2)
>>> 1
Is there something like that for numpy arrays?
[/INST] Yes, here is the answer given a Numpy array, array, and a val... |
<s>[INST] How to copy a dictionary and only edit the copy Can someone please explain this to me? This doesn't make any sense to me.
I copy a dictionary into another and edit the second and both are changed. Why is this happening?
>>> dict1 = {"key1": "value1", "key2": "value2"}
>>> dict2 = dict1
>>> dict2
{'key2': 'val... |
<s>[INST] Empty set literal in Python? [] = empty list
() = empty tuple
{} = empty dict
Is there a similar notation for an empty set?
Or do I have to write set()?
[/INST] No, there's no literal syntax for the empty set. You have to write set().
</s> |
<s>[INST] Django - what is the difference between render(), render_to_response() and direct_to_template()? Whats the difference (in language a python/django noob can understand) in a view between render(), render_to_response() and direct_to_template()?
e.g. from Nathan Borror's basic apps examples
def comment_edit(requ... |
<s>[INST] Unicode (utf8) reading and writing to files in python I'm having some brain failure in understanding reading and writing text to a file (Python 2.4).
# the string, which has an a-acute in it.
ss = u'Capit\xe1n'
ss8 = ss.encode('utf8')
repr(ss), repr(ss8)
("u'Capit\xe1n'", "'Capit\xc3\xa1n'")
print ss, ss8 ... |
<s>[INST] Create List of Single Item Repeated n Times in Python I know a list comprehension will do this, but I was wondering if there is an even shorter (and more Pythonic?) approach.
I want to create a series of lists, all of varying length. Each list will contain the same element e, repeated n times (where n = lengt... |
<s>[INST] How can I represent an infinite number in Python? In python, when you want to give to a set of elements an associated value, and you use this value for comparisons between them, I would want this value as infinite. No matter which number you enter in the program, no number will be greater than this represent... |
<s>[INST] What is the difference between Python's re.search and re.match? What is the difference between the search() and match() functions in the Python re module?
I've read the documentation (current documentation), but I never seem to remember it. I keep having to look it up and re-learn it. I'm hoping that someon... |
<s>[INST] Get key by value in dictionary I made a function which will look up ages in dictionary and show the matching name:
list = {'george':16,'amber':19}
search_age = raw_input("Provide age")
for age in list.values():
if age == search_age:
name = list[age]
print name
I know how to compare and fi... |
<s>[INST] Representing and solving a maze given an image What is the best way to represent and solve a maze given an image?
Given an JPEG image (as seen above), what's the best way to read it in, parse it into some data structure and solve the maze? My first instinct is to read the image in pixel by pixel and store it... |
<s>[INST] What is the standard way to add N seconds to datetime.time in Python? Given a datetime.time value in Python, is there a standard way to add an integer number of seconds to it, so that 11:34:59 + 3 = 11:35:02, for example?
These obvious ideas don't work:
>>> datetime.time(11, 34, 59) + 3
TypeError: unsupported... |
<s>[INST] Removing a list of characters in string I want to remove characters in a string in python:
string.replace(',', '').replace("!", '').replace(":", '').replace(";", '')...
But I have many characters I have to remove. I thought about a list
list = [',', '!', '.', ';'...]
But how can I use the list to replace th... |
<s>[INST] Plot logarithmic axes with matplotlib in python I want to plot a graph with one logarithmic axis using matplotlib.
I've been reading the docs, but can't figure out the syntax. I know that it's probably something simple like 'scale=linear' in the plot arguments, but I can't seem to get it right
Sample program... |
<s>[INST] PyPy -- How can it possibly beat CPython? From the Google Open Source Blog:
PyPy is a reimplementation of Python
in Python, using advanced techniques
to try to attain better performance
than CPython. Many years of hard work
have finally paid off. Our speed
results often beat CPython, ranging
from... |
<s>[INST] What does the 'b' character do in front of a string literal? Apparently, the following is valid syntax...
my_string = b'The string'
I would like to know...
What does this b character infront of the string mean?
What are the effects of using it?
What are appropriate situations to use it.
I found a related q... |
<s>[INST] add one row in a pandas.DataFrame I understand that pandas is designed to load fully populated DataFrame but I need to create an empty DataFrame then add rows, one by one.
What is the best way to do this ?
I successfully created an empty DataFrame with :
res = DataFrame(columns=('lib', 'qty1', 'qty2'))
Then ... |
<s>[INST] overloading __init__ in python Let's say I have a class that has a member called data which is a list.
I want to be able to initialize the class with, for example, a filename (which contains data to initialize the list) or with an actual list.
What's your technique for doing this?
Do you just check the type... |
<s>[INST] python ImportError No module named I am very new at Python and I am getting this error:
Traceback (most recent call last):
File "mountain.py", line 28, in ?
from toolkit.interface import interface
ImportError: No module named toolkit.interface
Python is installed in a local directory:
My directory tree... |
<s>[INST] How to delete a character from a string using python? There is a string, for example EXAMPLE
How can I remove the middle character i.e. M from it. I don't need the code, what I want to know is
Do strings in python end in any special character?
Which is a better way - shifting everything right to left startin... |
<s>[INST] What's the difference between raw_input() and input() in python3.x? What is the difference between raw_input() and input() in python3.x ?
[/INST] The difference is that raw_input() does not exist in Python 3.x, while input() does. Actually, the old raw_input() has been renamed to input(), and the old input(... |
<s>[INST] How to fix python indentation I have some python code that have inconsistent indentation, there is a lot of mixture of tabs and spaces to make the matter even worse even space indentation is not preserved.
The code works as expected but it's difficult to maintain.
How can I fix the indentation (like "html tid... |
<s>[INST] How do you create a daemon in Python? Searching on Google reveals x2 code snippets. The first result is to this code recipe which has a lot of documentation and explanation, along with some useful discussion underneath.
However, another code sample, whilst not containing so much documentation, includes sampl... |
<s>[INST] Wrapping a C library in Python: C, Cython or ctypes? I want to call a C library from a Python application. I don't want to wrap the whole API, only the functions and datatypes that are relevant to my case. As I see it, I have three choices:
Create an actual extension module in C. Probably overkill, and I'd a... |
<s>[INST] Get exception description and stack trace which caused an exception, all as a string I've seen a lot of posts about stack trace and exceptions in Python. But haven't found what I need.
I have a chunk of Python 2.7 code that may raise an exception. I would like to catch it and assign to a string its full descr... |
<s>[INST] Python int to binary? Are there any canned Python methods to convert an Integer (or Long) into a binary string in Python?
There are a myriad of dec2bin() functions out on Google... But I was hoping I could use a built-in function / library.
[/INST] Python's string format method can take a format spec.
>>> "... |
<s>[INST] Is it possible to break a long line to multiple lines in Python Just like C, you can break a long line into multiple short lines. But in Python, if I do this, there will be an indent error... Is it possible?
[/INST] From PEP 8 - Style Guide for Python Code:
The preferred way of wrapping long lines is by usi... |
<s>[INST] Why does python use 'else' after for and while loops? I understand how this construct works:
for i in range(10):
print(i)
if i == 9:
print("Too big - I'm giving up!")
break;
else:
print("Completed successfully")
But I don't understand why else is used as the keyword here, since i... |
<s>[INST] Why use argparse rather than optparse? I noticed that the Python 2.7 documentation includes yet another command-line parsing module. In addition to getopt and optparse we now have argparse.
Why has yet another command-line parsing module been created? Why should I use it instead of optparse? Are there new ... |
<s>[INST] python: how to import the class within the same directory or sub directory I have a directory that stores all the .py files.
bin/
main.py
user.py # where class User resides
dir.py # where class Dir resides
I want to use classes from user.py and dir.py in main.py.
How can I import these Python classe... |
<s>[INST] How can I check the syntax of Python script without executing it? I used to use perl -c programfile to check the syntax of a Perl program and then exit without executing it. Is there an equivalent way to do this for a Python script?
[/INST] You can check the syntax by compiling it:
python -m py_compile scrip... |
<s>[INST] Python in Xcode 7 How does one create a Python friendly environment in Xcode 7?
[/INST] I figured it out! The steps make it look like it will take more effort than it actually does.
These instructions are for creating a project from scratch. If you have existing Python scripts that you wish to include in thi... |
<s>[INST] Test if executable exists in Python? In Python, is there a portable and simple way to test if an executable program exists?
By simple I mean something like the which command which would be just perfect. I don't want to search PATH manually or something involving trying to execute it with Popen & al and see if... |
<s>[INST] How would you make a comma-separated string from a list? What would be your preferred way to concatenate strings from a sequence such that between each two consecutive pair a comma is added. That is, how do you map, for instance, [ 'a', 'b', 'c' ] to 'a,b,c'? (The cases [ s ] and [] should be mapped to s and ... |
<s>[INST] TypeError: 'module' object is not callable File "C:\Users\Administrator\Documents\Mibot\oops\blinkserv.py", line 82, in __init__
self.serv = socket(AF_INET,SOCK_STREAM)
TypeError: 'module' object is not callable
Why am I getting this error?
I'm confused.
What do you need to know to answer my question?
[... |
<s>[INST] Python thread pool similar to the multiprocessing Pool? Is there a Pool class for worker threads, similar to the multiprocessing module's Pool class?
I like for example the easy way to parallelize a map function
def long_running_func(p):
c_func_no_gil(p)
p = multiprocessing.Pool(4)
xs = p.map(long_runnin... |
<s>[INST] Python: import a file from a subdirectory I have a file called tester.py, located on /project.
/project has a subdirectory called lib, with a file called BoxTime.py:
/project/tester.py
/project/lib/BoxTime.py
I want to import BoxTime from tester. I have tried this:
import lib.BoxTime
Which resulted:
Traceba... |
<s>[INST] Can a variable number of arguments be passed to a function? In a similar way to using varargs in C or C++:
fn(a, b)
fn(a, b, c, d, ...)
[/INST] Yes.
This is simple and works if you disregard keyword arguments:
def manyArgs(*arg):
print "I was called with", len(arg), "arguments:", arg
>>> manyArgs(1)
I wa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.