Saturday 4 November 2017

Help on Python

Help on Python

execute the below command in python shell to launch help tool.

HELP

help()


>>> help()

Welcome to Python 3.6's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at http://docs.python.org/3.6/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".

help>


  • modules
  • keywords 
  • symbols
  • topics
  • type


modules

help> modules

Please wait a moment while I gather a list of all available modules...

invalid distro: 'Ubuntu'
AptUrl              apport_python_hook  hmac                sched
CommandNotFound     apt                 html                secrets
Crypto              aptdaemon           http                select
DistUpgrade         aptsources          httplib2            selectors
LanguageSelector    argparse            idlelib             shelve
NvidiaDetector      array               imaplib             shlex
Onboard             ast                 imghdr              shutil
Quirks              asynchat            imp                 signal
UbuntuDrivers       asyncio             importlib           site
UpdateManager       asyncore            inspect             sitecustomize
__future__          atexit              io                  six
_ast                audioop             ipaddress           smtpd
_asyncio            base64              itertools           smtplib
_bisect             bdb                 janitor             sndhdr
_blake2             binascii            json                socket
_bootlocale         binhex              keyword             socketserver
_bz2                bisect              language_support_pkgs softwarecenter_aptd_plugins
_codecs             builtins            lib2to3             softwareproperties
_codecs_cn          bytecode            linecache           speechd
_codecs_hk          bz2                 locale              speechd_config
_codecs_iso2022     cProfile            logging             spwd
_codecs_jp          cairo               louis               sqlite3
_codecs_kr          calendar            lsb_release         sre_compile
_codecs_tw          cgi                 lxml                sre_constants
_collections        cgitb               lzma                sre_parse
_collections_abc    chardet             macpath             ssl
_compat_pickle      checkbox_ng         macurl2path         stat
_compression        checkbox_support    mailbox             statistics
_crypt              chunk               mailcap             string
_csv                cmath               mako                stringprep
_ctypes             cmd                 markupsafe          struct
_ctypes_test        code                marshal             subprocess
_curses             codecs              math                sunau
_curses_panel       codeop              mimetypes           symbol
_datetime           collections         mmap                symtable
_dbm                colorsys            modulefinder        sys
_decimal            compileall          multiprocessing     sysconfig
_dummy_thread       concurrent          netrc               syslog
_elementtree        configparser        nis                 tabnanny
_functools          contextlib          nntplib             tarfile
_hashlib            copy                ntpath              telnetlib
_heapq              copyreg             nturl2path          tempfile
_imp                crypt               numbers             termios
_io                 csv                 oauthlib            test
_json               ctypes              oneconf             textwrap
_locale             curl                opcode              this
_lsprof             curses              operator            threading
_lzma               datetime            optparse            time
_markupbase         dbm                 orca                timeit
_md5                dbus                os                  tkinter
_multibytecodec     deb822              ossaudiodev         token
_multiprocessing    debconf             parser              tokenize
_opcode             debian              pathlib             trace
_operator           debian_bundle       pdb                 traceback
_osx_support        decimal             pickle              tracemalloc
_pickle             defer               pickletools         tty
_posixsubprocess    difflib             pipes               turtle
_pydecimal          dis                 piston_mini_client  types
_pyio               distutils           pkg_resources       typing
_random             doctest             pkgutil             ufw
_sha1               dummy_threading     plainbox            unicodedata
_sha256             email               platform            unittest
_sha3               encodings           plistlib            uno
_sha512             enum                poplib              unohelper
_signal             errno               posix               urllib
_sitebuiltins       faulthandler        posixpath           urllib3
_socket             fcntl               pprint              usbcreator
_sqlite3            feedparser          problem_report      uu
_sre                feedparser_sgmllib3 profile             uuid
_ssl                filecmp             pstats              venv
_stat               fileinput           pty                 warnings
_string             fnmatch             pwd                 wave
_strptime           formatter           py_compile          weakref
_struct             fpectl              pyatspi             webbrowser
_symtable           fractions           pyclbr              wsgiref
_sysconfigdata_m_linux_i386-linux-gnu friends             pydoc               xdg
_testbuffer         ftplib              pydoc_data          xdiagnose
_testcapi           functools           pyexpat             xdrlib
_testimportmultiple gc                  pygtkcompat         xkit
_testmultiphase     genericpath         pyparsing           xml
_thread             getopt              queue               xmlrpc
_threading_local    getpass             quopri              xxlimited
_tracemalloc        gettext             random              xxsubtype
_warnings           gi                  re                  zipapp
_weakref            glob                readline            zipfile
_weakrefset         gnome_sudoku        reprlib             zipimport
abc                 grp                 requests            zlib
aifc                gzip                resource
antigravity         hashlib             rlcompleter
apport              heapq               runpy

Enter any module name to get more help.  Or, type "modules spam" to search
for modules whose name or summary contain the string "spam".

Keywords

help> keywords

Here is a list of the Python keywords.  Enter any keyword to get more help.

False               def                 if                  raise
None                del                 import              return
True                elif                in                  try
and                 else                is                  while
as                  except              lambda              with
assert              finally             nonlocal            yield
break               for                 not
class               from                or
continue            global              pass


symbols

help> symbols

Here is a list of the punctuation symbols which Python assigns special meaning
to. Enter any symbol to get more help.

!=                  *=                  <<                  ^
"                   +                   <<=                 ^=
"""                 +=                  <=                  _
%                   ,                   <>                  __
%=                  -                   ==                  `
&                   -=                  >                   b"
&=                  .                   >=                  b'
'                   ...                 >>                  j
'''                 /                   >>=                 r"
(                   //                  @                   r'
)                   //=                 J                   |
*                   /=                  [                   |=
**                  :                   \                   ~
**=                 <                   ]

Tpoics

help> topics

Here is a list of available topics.  Enter any topic name to get more help.

ASSERTION           DELETION            LOOPING             SHIFTING
ASSIGNMENT          DICTIONARIES        MAPPINGMETHODS      SLICINGS
ATTRIBUTEMETHODS    DICTIONARYLITERALS  MAPPINGS            SPECIALATTRIBUTES
ATTRIBUTES          DYNAMICFEATURES     METHODS             SPECIALIDENTIFIERS
AUGMENTEDASSIGNMENT ELLIPSIS            MODULES             SPECIALMETHODS
BASICMETHODS        EXCEPTIONS          NAMESPACES          STRINGMETHODS
BINARY              EXECUTION           NONE                STRINGS
BITWISE             EXPRESSIONS         NUMBERMETHODS       SUBSCRIPTS
BOOLEAN             FLOAT               NUMBERS             TRACEBACKS
CALLABLEMETHODS     FORMATTING          OBJECTS             TRUTHVALUE
CALLS               FRAMEOBJECTS        OPERATORS           TUPLELITERALS
CLASSES             FRAMES              PACKAGES            TUPLES
CODEOBJECTS         FUNCTIONS           POWER               TYPEOBJECTS
COMPARISON          IDENTIFIERS         PRECEDENCE          TYPES
COMPLEX             IMPORTING           PRIVATENAMES        UNARY
CONDITIONAL         INTEGER             RETURNING           UNICODE
CONTEXTMANAGERS     LISTLITERALS        SCOPING
CONVERSIONS         LISTS               SEQUENCEMETHODS
DEBUGGING           LITERALS            SEQUENCES


help> type
Help on class type in module builtins:

class type(object)
 |  type(object_or_name, bases, dict)
 |  type(object) -> the object's type
 |  type(name, bases, dict) -> a new type
 |
 |  Methods defined here:
 |
 |  __call__(self, /, *args, **kwargs)
 |      Call self as a function.
 |
 |  __delattr__(self, name, /)
 |      Implement delattr(self, name).
 |
 |  __dir__(...)
 |      __dir__() -> list
 |      specialized __dir__ implementation for types
 |
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |
 |  __instancecheck__(...)
 |      __instancecheck__() -> bool
 |      check if an object is an instance
 |
 |  __new__(*args, **kwargs)
 |      Create and return a new object.  See help(type) for accurate signature.
 |
 |  __prepare__(...)
 |      __prepare__() -> dict
 |      used to create the namespace for the class statement
 |
 |  __repr__(self, /)
 |      Return repr(self).
 |
 |  __setattr__(self, name, value, /)
 |      Implement setattr(self, name, value).


Install Python3.6 on Ubuntu

Install Python3.6 on Ubuntu 


sudo add-apt-repository ppa:jonathonf/python-3.6
sudo apt-get update
sudo apt-get install python3.6
reference
https://askubuntu.com/questions/865554/how-do-i-install-python-3-6-using-apt-get

Python view Byte Code for the given script

Python view Byte Code for the given script


Normal execution syntax
python file_name.py

For retrieving the Byte Code information the execution syntax is,
python -m dist file_name.py

which will display in a disassembler format (human readable format)

Example :

# simple.py
a=10
b=20
c=a+b
print(c)

#output 
30


#cat bytecode.py

a=10
b=20
c=a+b
print(c)

#python3.6 bytecode.py

30

#python3.6 -m dis bytecode.py

  1           0 LOAD_CONST               0 (10)
              2 STORE_NAME               0 (a)

  2           4 LOAD_CONST               1 (20)
              6 STORE_NAME               1 (b)

  3           8 LOAD_NAME                0 (a)
             10 LOAD_NAME                1 (b)
             12 BINARY_ADD
             14 STORE_NAME               2 (c)

  4          16 LOAD_NAME                3 (print)
             18 LOAD_NAME                2 (c)
             20 CALL_FUNCTION            1
             22 POP_TOP
             24 LOAD_CONST               2 (None)
             26 RETURN_VALUE



Friday 3 November 2017

Python Microsoft Visual C++ 14.0 is required error while pip install

Python Microsoft Visual C++ 14.0 is required error while pip install


Error
-------

Collecting dist
  Using cached dist-1.0.3.zip
Installing collected packages: dist
  Running setup.py install for dist: started
    Running setup.py install for dist: finished with status 'error'
    Complete output from command C:\Python36-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\alps\\AppData\\Local\\Temp\\pycharm-packaging\\dist\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\alps\AppData\Local\Temp\pip-62o9v2z5-record\install-record.txt --single-version-externally-managed --compile:
    running install
    running build
    running build_ext
    building 'dist' extension
    error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
 
    ----------------------------------------

Command "C:\Python36-32\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\alps\\AppData\\Local\\Temp\\pycharm-packaging\\dist\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\alps\AppData\Local\Temp\pip-62o9v2z5-record\install-record.txt --single-version-externally-managed --compile" failed with error code 1 in C:\Users\alps\AppData\Local\Temp\pycharm-packaging\dist\


pytho 3.x required "Microsoft Visual C++ 14.0"


before that install dotnet 4.5.1 which will be the minimum required version to be available on the machine before executing MS visutal c++ 14.0
https://www.microsoft.com/en-in/download/details.aspx?id=40779
so post installing python dont forget to install the package which can be downloaded from
http://landinghub.visualstudio.com/visual-cpp-build-tools

post installation restart the machine to take effect the changes

How to create compiled files in python (py to pyc conversion)

How to create compiled files in python (py to pyc conversion)

This post explains about generating compiled files in python(py to pyc conversion).

The syntax is given as follows,

python -m py_compile file_name.py

where,
python is the executor command
-m is to represent the module
py_compile is the module to be called
file_name.py is the actual file which has to be compiled

This will create a output file like file_name.cpython.pyc

Thursday 2 March 2017

Python 3 While Loop

Python 3 While Loop

The below code block is an example for python while loop

'''While loops'''
a = 11
while a>10:
    a+=1
    print (a)
    break       # prints 12 and then breaks

Wednesday 1 March 2017

Python 3 Conditional Operators

Python 3 Conditional Operators

The explanation programs for conditional operators is as follows,

'''Conditional Operation'''
a = 100
if a == 100:
    print ("true")
else:
    print ("false")

# result is true
if a <50:
    print ("less than 50")
else:
    if a > 50:
        print ("greater than 50")

# result is greater than 50
if a < 50:
    print ("less than 50")
elif a>50:
    print ("greater than 50")
    
# result is greater than 50