Python Pandas – Missing required dependencies [numpy] 1

Python Pandas – Missing required dependencies [numpy] 1

I had this same issue immediately after upgrading pandas to 0.19.2. I fixed it with the following install/uninstall sequence from the windows cmd line:

pip uninstall pandas -y
pip uninstall numpy -y
pip install pandas
pip install numpy

This also broke my matplotlib install so I uninstalled/installed that as well.

Very odd behavior for a seemingly routine upgrade.

What happens if you try to import numpy?

Have you tried

pip install --upgrade numpy
pip install --upgrade pandas

Python Pandas – Missing required dependencies [numpy] 1

I had to install this other package:

Python Pandas – Missing required dependencies [numpy] 1

sudo apt-get install libatlas-base-dev

Seems like it is a dependency for numpy but the pip or apt-get dont install it automatically for whatever reason.

How can I remove a key from a Python dictionary?

How can I remove a key from a Python dictionary?

To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop():

my_dict.pop(key, None)

This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (i.e. my_dict.pop(key)) and key does not exist, a KeyError is raised.

To delete a key that is guaranteed to exist, you can also use:

del my_dict[key]

This will raise a KeyError if the key is not in the dictionary.

Specifically to answer is there a one line way of doing this?

if key in my_dict: del my_dict[key]

…well, you asked 😉

You should consider, though, that this way of deleting an object from a dict is not atomic—it is possible that key may be in my_dict during the if statement, but may be deleted before del is executed, in which case del will fail with a KeyError. Given this, it would be safest to either use dict.pop or something along the lines of

try:
    del my_dict[key]
except KeyError:
    pass

which, of course, is definitely not a one-liner.

How can I remove a key from a Python dictionary?

How can I remove a key from a Python dictionary?

It took me some time to figure out what exactly my_dict.pop(key, None) is doing. So Ill add this as an answer to save others googling time:

pop(key[, default])

If key is in the dictionary, remove it and return its value, else
return default. If default is not given and key is not in the
dictionary, a KeyError is raised.

Documentation

How to disable Python warnings?

How to disable Python warnings?

Look at the Temporarily Suppressing Warnings section of the Python docs:

If you are using code that you know will raise a warning, such as a deprecated function, but do not want to see the warning, then it is possible to suppress the warning using the catch_warnings context manager:

import warnings

def fxn():
    warnings.warn(deprecated, DeprecationWarning)

with warnings.catch_warnings():
    warnings.simplefilter(ignore)
    fxn()

I dont condone it, but you could just suppress all warnings with this:

import warnings
warnings.filterwarnings(ignore)

Ex:

>>> import warnings
>>> def f():
...     print(before)
...     warnings.warn(you are warned!)
...     print(after)
...
>>> f()
before
<stdin>:3: UserWarning: you are warned!
after
>>> warnings.filterwarnings(ignore)
>>> f()
before
after

Theres the -W option.

python -W ignore foo.py

How to disable Python warnings?

You can also define an environment variable (new feature in 2010 – i.e. python 2.7)

How to disable Python warnings?

export PYTHONWARNINGS=ignore

Test like this: Default

$ export PYTHONWARNINGS=default
$ python
>>> import warnings
>>> warnings.warn(my warning)
__main__:1: UserWarning: my warning
>>>

Ignore warnings

$ export PYTHONWARNINGS=ignore
$ python
>>> import warnings
>>> warnings.warn(my warning)
>>> 

For deprecation warnings have a look at how-to-ignore-deprecation-warnings-in-python

Copied here…

From documentation of the warnings module:

 #!/usr/bin/env python -W ignore::DeprecationWarning

If youre on Windows: pass -W ignore::DeprecationWarning as an argument to Python. Better though to resolve the issue, by casting to int.

(Note that in Python 3.2, deprecation warnings are ignored by default.)

Or:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings(ignore, category=DeprecationWarning)
    import md5, sha

yourcode()

Now you still get all the other DeprecationWarnings, but not the ones caused by:

import md5, sha

python – How to convert string to binary?

python – How to convert string to binary?

Something like this?

>>> st = hello world
>>>  .join(format(ord(x), b) for x in st)
1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100

#using `bytearray`
>>>  .join(format(x, b) for x in bytearray(st, utf-8))
1101000 1100101 1101100 1101100 1101111 100000 1110111 1101111 1110010 1101100 1100100

If by binary you mean bytes type, you can just use encode method of the string object that encodes your string as a bytes object using the passed encoding type. You just need to make sure you pass a proper encoding to encode function.

In [9]: hello world.encode(ascii)                                                                                                                                                                       
Out[9]: bhello world

In [10]: byte_obj = hello world.encode(ascii)                                                                                                                                                           

In [11]: byte_obj                                                                                                                                                                                           
Out[11]: bhello world

In [12]: byte_obj[0]                                                                                                                                                                                        
Out[12]: 104

Otherwise, if you want them in form of zeros and ones –binary representation– as a more pythonic way you can first convert your string to byte array then use bin function within map :

>>> st = hello world
>>> map(bin,bytearray(st))
[0b1101000, 0b1100101, 0b1101100, 0b1101100, 0b1101111, 0b100000, 0b1110111, 0b1101111, 0b1110010, 0b1101100, 0b1100100]
 

Or you can join it:

>>>  .join(map(bin,bytearray(st)))
0b1101000 0b1100101 0b1101100 0b1101100 0b1101111 0b100000 0b1110111 0b1101111 0b1110010 0b1101100 0b1100100

Note that in python3 you need to specify an encoding for bytearray function :

>>>  .join(map(bin,bytearray(st,utf8)))
0b1101000 0b1100101 0b1101100 0b1101100 0b1101111 0b100000 0b1110111 0b1101111 0b1110010 0b1101100 0b1100100

You can also use binascii module in python 2:

>>> import binascii
>>> bin(int(binascii.hexlify(st),16))
0b110100001100101011011000110110001101111001000000111011101101111011100100110110001100100

hexlify return the hexadecimal representation of the binary data then you can convert to int by specifying 16 as its base then convert it to binary with bin.

python – How to convert string to binary?

We just need to encode it.

python – How to convert string to binary?

string.encode(ascii)

macos – How to change default Python version?

macos – How to change default Python version?

[updated for 2021]

(Regardless if you are on Mac, Linux, or Windows:)

If you are confused about how to start the latest version of python, on most platforms it is the case that python3 leaves your python2 installation intact (due to the above compatibility reasons); thus you can start python3 with the python3 command.

Historically…

The naming convention is that generally, most scripts will call python2 or python3 explicitly. This happened due to a need for backwards compatibility.

Even though technically python doesnt even guarantee backwards compatibility between minor versions, Python3 really breaks backwards compatibility. At the time, programs invoking python were expecting python2 (which was the main version at the time). Extremely old systems may have programs and scripts which expect python=python2, and changing this would break those programs and scripts.

At the time this answer was written, OP should not have changed this due to maintaining compatibility for old scripts.

Circa year 2021…

Nowadays, many years after the python2->python3 transition, most software explicitly refers to python2 or python3 (at least on Linux). For example, they might call #!/usr/bin/env python2 or #!/usr/bin/env python3. This has for example (python-is-python3-package) freed up the python command to be settable to a user default, but it really depends on the operating system.

The prescription for how distributions should handle the python command was written up in 2011 as PEP 394 — The python Command on Unix-Like Systems. It was last updated in June 2019.

Basically if you are writing a library, you should use the most specific version(s) of python you can use. Otherwise as an end user, you should feel free to rename this for your own personal use (though your OS or distribution may not make that easy).

Shell alias:

You could, however, make a custom alias in your shell. The way you do so depends on the shell, but perhaps you could do alias py=python3, and put it in your shell startup file. This will only work on your local computer (as it should), and is somewhat unnecessary compared to just typing it out (unless you invoke the command constantly).

Confused users should not try to create aliases or virtual environments or similar that make python execute python3; this is poor form.This is acceptable nowadays, but PEP 394 suggests encouraging users to use a virtualenv instead.

Different 3.* versions, or 2.* versions:

In the extremely unlikely case that if someone comes to this question with two python3 versions e.g. 3.1 vs 3.2, and you are confused that you have somehow installed two versions of python, this is possibly because you have done manual and/or manual installations. You can use your OSs standard package/program install/uninstall/management facilities to help track things down, and perhaps (unless you are doing dev work that surprisingly is impacted by the few backwards-incompatible changes between minor versions) delete the old version (or do make uninstall if you did a manual installation). If you require two versions, then reconfigure your $PATH variable so the default version you want is in front; or if you are using most Linux distros, the command you are looking for is sudo update-alternatives. Make sure any programs you run which need access to the older versions may be properly invoked by their calling environment or shell (by setting up the var PATH in that environment).

A bit about $PATH

sidenote: To elaborate a bit on PATH: the usual ways that programs are selected is via the PATH (echo $PATH on Linux and Mac) environment variable. You can always run a program with the full path e.g. /usr/bin/ some args, or cd /usr/bin then ./ some args (replace blank with the echo program I mentioned above for example), but otherwise typing some args has no meaning without PATH env variable which declares the directories we implicitly may search-then-execute files from (if /usr/bin was not in PATH, then it would say : command not found). The first matching command in the first directory is the one which is executed (the which command on Linux and Mac will tell you which sub-path this is). Usually it is (e.g. on Linux, but similar on Mac) something like /usr/bin/python which is a symlink to other symlinks to the final version somewhere, e.g.:

% echo $PATH
/usr/sbin:/usr/local/bin:/usr/sbin:usr/local/bin:/usr/bin:/bin

% which python
/usr/bin/python
% which python2
/usr/bin/python2
% ls -l /usr/bin/python
lrwxrwxrwx 1 root root 7 Mar  4  2019 /usr/bin/python -> python2*
% ls -l /usr/bin/python2  
lrwxrwxrwx 1 root root 9 Mar  4  2019 /usr/bin/python2 -> python2.7*
% ls -l /usr/bin/python2.7
-rwxr-xr-x 1 root root 3689352 Oct 10  2019 /usr/bin/python2.7*

% which python3         
/usr/bin/python3
% ls -l /usr/bin/python3
lrwxrwxrwx 1 root root 9 Mar 26  2019 /usr/bin/python3 -> python3.7*
% ls -l /usr/bin/python3.7
-rwxr-xr-x 2 root root 4877888 Apr  2  2019 /usr/bin/python3.7*

% ls -l /usr/bin/python*
lrwxrwxrwx 1 root root       7 Mar  4  2019 /usr/bin/python -> python2*
lrwxrwxrwx 1 root root       9 Mar  4  2019 /usr/bin/python2 -> python2.7*
-rwxr-xr-x 1 root root 3689352 Oct 10  2019 /usr/bin/python2.7*
lrwxrwxrwx 1 root root       9 Mar 26  2019 /usr/bin/python3 -> python3.7*
-rwxr-xr-x 2 root root 4877888 Apr  2  2019 /usr/bin/python3.7*
lrwxrwxrwx 1 root root      33 Apr  2  2019 /usr/bin/python3.7-config -> x86_64-linux-gnu-python3.7-config*
-rwxr-xr-x 2 root root 4877888 Apr  2  2019 /usr/bin/python3.7m*
lrwxrwxrwx 1 root root      34 Apr  2  2019 /usr/bin/python3.7m-config -> x86_64-linux-gnu-python3.7m-config*
lrwxrwxrwx 1 root root      16 Mar 26  2019 /usr/bin/python3-config -> python3.7-config*
lrwxrwxrwx 1 root root      10 Mar 26  2019 /usr/bin/python3m -> python3.7m*
lrwxrwxrwx 1 root root      17 Mar 26  2019 /usr/bin/python3m-config -> python3.7m-config*

sidenote2: (In the rarer case a python program invokes a sub-program with the subprocess module, to specify which program to run, one can modify the paths of subprocesses with sys.path from the sys module or the PYTHONPATH environment variable set on the parent, or specifying the full path… but since the path is inherited by child processes this is not remotely likely an issue.)

Check the location of python 3

$ which python3
/usr/local/bin/python3

Write alias in bash_profile

vi ~/.bash_profile  
alias python=/usr/local/bin/python3

Reload bash_profile

source ~/.bash_profile

Confirm python command

$ python --version
Python 3.6.5

macos – How to change default Python version?

On Mac OS X using the python.org installer as you apparently have, you need to invoke Python 3 with python3, not python. That is currently reserved for Python 2 versions. You could also use python3.2 to specifically invoke that version.

$ which python
/usr/bin/python
$ which python3
/Library/Frameworks/Python.framework/Versions/3.2/bin/python3
$ cd /Library/Frameworks/Python.framework/Versions/3.2/bin/
$ ls -l
total 384
lrwxr-xr-x  1 root  admin      8 Apr 28 15:51 [email protected] -> 2to3-3.2
-rwxrwxr-x  1 root  admin    140 Feb 20 11:14 2to3-3.2*
lrwxr-xr-x  1 root  admin      7 Apr 28 15:51 [email protected] -> idle3.2
-rwxrwxr-x  1 root  admin    138 Feb 20 11:14 idle3.2*
lrwxr-xr-x  1 root  admin      8 Apr 28 15:51 [email protected] -> pydoc3.2
-rwxrwxr-x  1 root  admin    123 Feb 20 11:14 pydoc3.2*
-rwxrwxr-x  2 root  admin  25624 Feb 20 11:14 python3*
lrwxr-xr-x  1 root  admin     12 Apr 28 15:51 [email protected] -> python3.2-32
lrwxr-xr-x  1 root  admin     16 Apr 28 15:51 [email protected] -> python3.2-config
-rwxrwxr-x  2 root  admin  25624 Feb 20 11:14 python3.2*
-rwxrwxr-x  1 root  admin  13964 Feb 20 11:14 python3.2-32*
lrwxr-xr-x  1 root  admin     17 Apr 28 15:51 [email protected] -> python3.2m-config
-rwxrwxr-x  1 root  admin  25784 Feb 20 11:14 python3.2m*
-rwxrwxr-x  1 root  admin   1865 Feb 20 11:14 python3.2m-config*
lrwxr-xr-x  1 root  admin     10 Apr 28 15:51 [email protected] -> pythonw3.2
lrwxr-xr-x  1 root  admin     13 Apr 28 15:51 [email protected] -> pythonw3.2-32
-rwxrwxr-x  1 root  admin  25624 Feb 20 11:14 pythonw3.2*
-rwxrwxr-x  1 root  admin  13964 Feb 20 11:14 pythonw3.2-32*

If you also installed a Python 2 from python.org, it would have a similar framework bin directory with no overlapping file names (except for 2to3).

$ open /Applications/Python 2.7/Update Shell Profile.command
$ sh -l
$ echo $PATH
/Library/Frameworks/Python.framework/Versions/2.7/bin:/Library/Frameworks/Python.framework/Versions/3.2/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
$ which python3
/Library/Frameworks/Python.framework/Versions/3.2/bin/python3
$ which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
$ cd /Library/Frameworks/Python.framework/Versions/2.7/bin
$ ls -l
total 288
-rwxrwxr-x  1 root  admin    150 Jul  3  2010 2to3*
lrwxr-x---  1 root  admin      7 Nov  8 23:14 [email protected] -> idle2.7
-rwxrwxr-x  1 root  admin    138 Jul  3  2010 idle2.7*
lrwxr-x---  1 root  admin      8 Nov  8 23:14 [email protected] -> pydoc2.7
-rwxrwxr-x  1 root  admin    123 Jul  3  2010 pydoc2.7*
lrwxr-x---  1 root  admin      9 Nov  8 23:14 [email protected] -> python2.7
lrwxr-x---  1 root  admin     16 Nov  8 23:14 [email protected] -> python2.7-config
-rwxrwxr-x  1 root  admin  33764 Jul  3  2010 python2.7*
-rwxrwxr-x  1 root  admin   1663 Jul  3  2010 python2.7-config*
lrwxr-x---  1 root  admin     10 Nov  8 23:14 [email protected] -> pythonw2.7
-rwxrwxr-x  1 root  admin  33764 Jul  3  2010 pythonw2.7*
lrwxr-x---  1 root  admin     11 Nov  8 23:14 [email protected] -> smtpd2.7.py
-rwxrwxr-x  1 root  admin  18272 Jul  3  2010 smtpd2.7.py*

Related posts

How do you get the logical xor of two variables in Python?

How do you get the logical xor of two variables in Python?

If youre already normalizing the inputs to booleans, then != is xor.

How do you get the logical xor of two variables in Python?

bool(a) != bool(b)

You can always use the definition of xor to compute it from other logical operations:

(a and not b) or (not a and b)

But this is a little too verbose for me, and isnt particularly clear at first glance. Another way to do it is:

bool(a) ^ bool(b)

The xor operator on two booleans is logical xor (unlike on ints, where its bitwise). Which makes sense, since bool is just a subclass of int, but is implemented to only have the values 0 and 1. And logical xor is equivalent to bitwise xor when the domain is restricted to 0 and 1.

So the logical_xor function would be implemented like:

def logical_xor(str1, str2):
    return bool(str1) ^ bool(str2)

Credit to Nick Coghlan on the Python-3000 mailing list.

How do you get the logical xor of two variables in Python?

How do you get the logical xor of two variables in Python?

Bitwise exclusive-or is already built-in to Python, in the operator module (which is identical to the ^ operator):

from operator import xor
xor(bool(a), bool(b))  # Note: converting to bools is essential

Related posts

python – Purpose of %matplotlib inline

python – Purpose of %matplotlib inline

%matplotlib is a magic function in IPython. Ill quote the relevant documentation here for you to read for convenience:

IPython has a set of predefined ‘magic functions’ that you can call with a command line style syntax. There are two kinds of magics, line-oriented and cell-oriented. Line magics are prefixed with the % character and work much like OS command-line calls: they get as an argument the rest of the line, where arguments are passed without parentheses or quotes. Lines magics can return results and can be used in the right hand side of an assignment. Cell magics are prefixed with a double %%, and they are functions that get as an argument not only the rest of the line, but also the lines below it in a separate argument.

%matplotlib inline sets the backend of matplotlib to the inline backend:

With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.

When using the inline backend, your matplotlib graphs will be included in your notebook, next to the code. It may be worth also reading How to make IPython notebook matplotlib plot inline for reference on how to use it in your code.

If you want interactivity as well, you can use the nbagg backend with %matplotlib notebook (in IPython 3.x), as described here.

Provided you are running IPython, the %matplotlib inline will make your plot outputs appear and be stored within the notebook.

According to documentation

To set this up, before any plotting or import of matplotlib is
performed you must execute the %matplotlib magic command. This
performs the necessary behind-the-scenes setup for IPython to work
correctly hand in hand with matplotlib; it does not, however,
actually execute any Python import commands, that is, no names are
added to the namespace.

A particularly interesting backend, provided by IPython, is the
inline backend. This is available only for the Jupyter Notebook and
the Jupyter QtConsole. It can be invoked as follows:

%matplotlib inline

With this backend, the output of plotting commands is displayed inline
within frontends like the Jupyter notebook, directly below the code
cell that produced it. The resulting plots will then also be stored in
the notebook document.

python – Purpose of %matplotlib inline

To explain it clear:

If you dont like it like this:

enter

add %matplotlib inline

enter

and there you have it in your jupyter notebook.
Related posts

connection – Connecting Python with Teradata using Teradata module

connection – Connecting Python with Teradata using Teradata module

There are a number of ways to connect to Teradata and export table to Pandas. Here are four+:

Using teradata module

# You can install teradata via PIP: pip install teradata
# to get a list of your odbc drivers names, you could do: teradata.tdodbc.drivers
# You don’t need to install teradata odbc driver if using method=rest.     
# See sending data from df to teradata for connection example 

import teradata
import pandas as pd

host,username,password = HOST,UID, PWD
#Make a connection
udaExec = teradata.UdaExec (appName=test, version=1.0, logConsole=False)


with udaExec.connect(method=odbc,system=host, username=username,
                            password=password, driver=DRIVERNAME) as connect:

    query = SELECT * FROM DATABASEX.TABLENAMEX;

    #Reading query to df
    df = pd.read_sql(query,connect)
    # do something with df,e.g.
    print(df.head()) #to see the first 5 rows

Using TeradataSQL

from @ymzkala : This package doesnt require you to install Teradata drivers (other than this package).

# Installing python -m pip install teradatasql

import teradatasql

with teradatasql.connect(host=host, user=username, password=password) as connect:
    df = pd.read_sql(query, connect)

Using pyodbc module

import pyodbc

 #You can install teradata via PIP: pip install pyodbc
 #to get a list of your odbc drivers names, you could do: pyodbc.drivers()

#Make a connection
link = DRIVER={DRIVERNAME};DBCNAME={hostname};UID={uid};PWD={pwd}.format(
                      DRIVERNAME=DRIVERNAME,hostname=hostname,  
                      uid=username, pwd=password)
with pyodbc.connect(link,autocommit=True) as connect:

    #Reading query to df
    df = pd.read_sql(query,connect)

Using sqlalchemy Module

 #You can install sqlalchemy via PIP: pip install sqlalchemy-teradata
 #Note: It is not pip install sqlalchemy. If you already have sqlalchemy, you still need sqlalchemy-teradata to get teradata dialects

from sqlalchemy import create_engine

#Make a connection

link = teradata://{username}:{password}@{hostname}/?driver={DRIVERNAME}.format(
               username=username,hostname=hostname,DRIVERNAME=DRIVERNAME)

with create_engine(link) as connect:

    #Reading query to df
    df = pd.read_sql(query,connect)

There is a fifth way, using giraffez module. I enjoy using this module as it come with MLOAD, FASTLOAD, BULKEXPORT etc. The only issue for beginners is its requirements (e.g C/C++ compiler ,Teradata CLIv2 and TPT API headers/lib files).

Note: Updated 13-07-2018, using of context manager to ensure closing of sessions

Update: 31-10-2018: Using teradata to send data from df to teradata

We can send data from df to Teradata. Avoiding odbc 1 MB limit and odbc driver dependency, we can use rest method. We need host ip_address, instead of driver argument. NB: The order of columns in df should match the order of columns in Teradata table.

import teradata
import pandas as pd

# HOST_IP can be found by executing *>>nslookup viewpoint* or *ping  viewpoint* 
udaExec = teradata.UdaExec (appName=test, version=1.0, logConsole=False) 
with udaExec.connect(method=rest,system=DBName, username=UserName,
                      password=Password, host=HOST_IP_ADDRESS) as connect:

    data = [tuple(x) for x in df.to_records(index=False)]

    connect.executemany(INSERT INTO DATABASE.TABLEWITH5COL values(?,?,?,?,?),data,batch=True)

Using odbc, you have to chunk your data to less than 1MB chunks to avoid [HY001][Teradata][ODBC Teradata Driver] Memory allocation error error: E.g.

import teradata
import pandas as pd
import numpy as np

udaExec = teradata.UdaExec (appName=test, version=1.0, logConsole=False)

with udaExec.connect(method=odbc,system=DBName, username=UserName,
                      password=Password, driver=DriverName) as connect:

    #We can divide our huge_df to small chuncks. E.g. 100 churchs
    chunks_df = np.array_split(huge_df, 100)

    #Import chuncks to Teradata
    for i,_ in enumerate(chunks_df):

        data = [tuple(x) for x in chuncks_df[i].to_records(index=False)]
        connect.executemany(INSERT INTO DATABASE.TABLEWITH5COL values(?,?,?,?,?),data,batch=True)

To add on to Praysons answer, you can use the teradatasql package (found on pypi). This package doesnt require you to install Teradata drivers (other than this package). Use it like so:

import teradatasql
import pandas as pd

with teradatasql.connect(host=host, user=username, password=password) as connect:
    data = pd.read_sql(select top 5 * from table_name;, connect)

connection – Connecting Python with Teradata using Teradata module

Download the Teradata Python module and python pyodbc.pyd from internet.
Install using cmd install setup.py.

Here is the sample script for connecting to teradata and extracting data:

import teradata
import pyodbc
import sys



udaExec = teradata.UdaExec (appName=HelloWorld, version=1.0,
        logConsole=False)

session = udaExec.connect(method=odbc, dsn=prod32,
        username=PRODRUN, password=PRODRUN);

i = 0
REJECTED = R;

f = file(output.txt,w);sys.stdout=f

cursor =  session.cursor();

ff_remaining = 0;

cnt = cursor.execute(SELECT  SEQ_NO,FRQFBKDC,PNR_RELOC FROM ttemp.ffremaining ORDER BY 1,2,3 ).rowcount;
rows = cursor.execute(SELECT  SEQ_NO,FRQFBKDC,PNR_RELOC FROM ttemp.ffremaining ORDER BY 1,2,3 ).fetchall();


for i in range(cnt):
    ff_remaining = cursor.execute(select count(*) as coun from  ttemp.ffretroq_paxoff where seq_no=? and status <> ?,(rows[i].seq_no,REJECTED)).fetchall();
    print ff_remaining[0].coun, rows[i].seq_no, REJECTED;

Related posts

printing – How to print to stderr in Python?

printing – How to print to stderr in Python?

I found this to be the only one short, flexible, portable and readable:

# This line only if you still care about Python2
from __future__ import print_function

import sys

def eprint(*args, **kwargs):
    print(*args, file=sys.stderr, **kwargs)

The optional function eprint saves some repetition. It can be used in the same way as the standard print function:

>>> print(Test)
Test
>>> eprint(Test)
Test
>>> eprint(foo, bar, baz, sep=---)
foo---bar---baz
import sys
sys.stderr.write()

Is my choice, just more readable and saying exactly what you intend to do and portable across versions.

Edit: being pythonic is a third thought to me over readability and performance… with these two things in mind, with python 80% of your code will be pythonic. list comprehension being the big thing that isnt used as often (readability).

printing – How to print to stderr in Python?

Python 2:

Also Read: printing – How to print to stderr in Python?

print >> sys.stderr, fatal error

Python 3:

print(fatal error, file=sys.stderr)

Long answer

print >> sys.stderr is gone in Python3.
http://docs.python.org/3.0/whatsnew/3.0.html says:

Old: print >> sys.stderr, fatal error
New: print(fatal error, file=sys.stderr)

For many of us, it feels somewhat unnatural to relegate the destination to the end of the command. The alternative

sys.stderr.write(fatal errorn)

looks more object oriented, and elegantly goes from the generic to the specific. But note that write is not a 1:1 replacement for print.

python – How to terminate a script?

python – How to terminate a script?

import sys
sys.exit()

details from the sys module documentation:

sys.exit([arg])

Exit from Python. This is implemented by raising the
SystemExit exception, so cleanup actions specified by finally clauses
of try statements are honored, and it is possible to intercept the
exit attempt at an outer level.

The optional argument arg can be an integer giving the exit status
(defaulting to zero), or another type of object. If it is an integer,
zero is considered “successful termination” and any nonzero value is
considered “abnormal termination” by shells and the like. Most systems
require it to be in the range 0-127, and produce undefined results
otherwise. 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. If another type of object
is passed, None is equivalent to passing zero, and any other object is
printed to stderr and results in an exit code of 1. In particular,
sys.exit(some error message) is a quick way to exit a program when
an error occurs.

Since exit() ultimately “only” raises an exception, it will only exit
the process when called from the main thread, and the exception is not
intercepted.

Note that this is the nice way to exit. @glyphtwistedmatrix below points out that if you want a hard exit, you can use os._exit(*errorcode*), though its likely os-specific to some extent (it might not take an errorcode under windows, for example), and it definitely is less friendly since it doesnt let the interpreter do any cleanup before the process dies. On the other hand, it does kill the entire process, including all running threads, while sys.exit() (as it says in the docs) only exits if called from the main thread, with no other threads running.

A simple way to terminate a Python script early is to use the built-in quit() function. There is no need to import any library, and it is efficient and simple.

Example:

#do stuff
if this == that:
  quit()

python – How to terminate a script?

Another way is:

Also Read: python – How to terminate a script?

raise SystemExit