Skip to main content

Python alias commands that play nice with virtualenv

There are plenty of predefined Python executables, symlinks, and aliases that come bundled with your operating system. These commands come in very handy because it saves you from typing out long commands or chain of scripts. However the downfall of operating system aliases is that they don’t always play nice with virtualenv (or venv if you’re on Python 3). Most predefined aliases use the system’s default Python as the interpreter, which is next to useless when your application runs in a virtual environment. Over the years, I’ve come up with my own Python aliases that play nice with virtual environments. For this post, I tried to stay as generic as possible such that any alias here can be used by every Pythonista. In other words, there will be no aliases for specific frameworks such as running a Django server or starting a Scrappy spider. The following is one of my bash scripts I source:

.py-aliases

#----- Pip -----#
alias pip-list="pip freeze | less"
alias pip-search="pip freeze | grep -i"
alias pip-remove="pip uninstall"
alias pip-upgrade="pip install -U"
alias pip-upgrade-all="pip freeze --local | grep -v '^\-e' | cut -d = -f 1|xargs -n1 pip install -U"

#----- Debugging -----#
alias pdb="python -m pdb"
alias ppjson="python -m json.tool"
alias module-locate="python -c 'from imp import find_module;from sys import argv;print(find_module(argv[1])[1])'"

#----- Documentation -----#
alias pydoc="python -m pydoc"

Pip

This set of commands is the most convenient because pip can be a bit awkward when installing, uninstalling, and upgrading modules. Astute dev-ops folks might notice that I took heavy inspiration from tools like apt-get and yum. These commands also imitate conda, so for those who are using Anaconda, checkout conda out.

  • pip-list: List all installed modules then pipe to a cursor so that it’s easy to scroll.
  • pip-search: Search installed Python modules
  • pip-remove: Uninstall Python module(s)
  • pip-upgrade: Upgrade Python module(s)
  • pip-upgrade-all: My favorite for development. Upgrades all the Python packages without the need to specifying them individually.

Debugging

  • pdb: This is self explanatory for veterans. Runs scripts in the environment’s Python debugger.
  • ppjson: Pretty print JSON from a file or curl output. If you work with JSON and RESTful web apps, then you need this!
  • module-locate: Locate the system file path to a particular Python module, which can be useful when debugging. This is actually a script on my machine, but to keep this post brief, I did a quick one-liner to capture the gist of my script.

Let's do a quick tutorial of ppjson. I generally use this to test JSON responses from web apps in conjunction with curl, treq, and/or requests. For example, lets get some Star Wars JSON from SWAPI and pipe it to our new ppjson alias:

curl -L http://swapi.co/api/people/1 | ppjson
{
      "name": "Luke Skywalker",
      "height": "1.72 m",
      "mass": "77 Kg",
      "hair_color": "Blond",
      "skin_color": "Caucasian",
      "eye_color": "Blue",
      "birth_year": "19 BBY",
      "gender": "Male",
      "homeworld": "http://swapi.co/api/planets/1/",
      "films": [
          "http://swapi.co/api/films/1/",
          "http://swapi.co/api/films/2/",
          "http://swapi.co/api/films/3/"
      ],
      "species": [
          "http://swapi.co/api/species/1/"
      ],
      "vehicles": [
          "http://swapi.co/api/vehicles/14/",
          "http://swapi.co/api/vehicles/30/"
      ],
      "starships": [
          "http://swapi.co/api/starships/12/",
          "http://swapi.co/api/starships/22/"
      ],
      "created": "2014-12-09T13:50:51.644000Z",
      "edited": "2014-12-10T13:52:43.172000Z",
      "url": "http://swapi.co/api/people/1/"
}

ppjson also works with files containing JSON.

Documentation

  • pydoc: Reference the environment PyDocs. This is generally very helpful (despite the HTML pages looking very ugly) when you need to get documentation of a module in your virutalenv. I regularly start the web server so that I can quickly reference builtin and installed modules without the need to google. Example: pydoc -b -p 9001

Comments

  1. For a simple version of module-locate:

    $ pip install e
    $ python -me pytest
    /home/tom/.virtualenvs/connect4/lib/python3.6/site-packages/pytest.py

    Literally 'python me' this 'python me' that! https://pypi.python.org/pypi/e

    ReplyDelete
  2. Here are some shortcuts, which I find extremely helpful:

    function pylib() {
    "$BROWSER" "https://docs.python.org/3/library/$1.html"
    }

    function pylib2() {
    "$BROWSER" "https://docs.python.org/2/library/$1.html"
    }

    function pypi() {
    "$BROWSER" "https://pypi.python.org/pypi/$1"
    }

    (I usually have set BROWSER to "xdg-open".)

    ReplyDelete
  3. I really appreciate information shared above. It’s of great help.

    python online training india

    ReplyDelete
  4. I was very much confused what to do next in my career, but after going through this article I got a clear version of undergoing Python Training in Chennai| Python Course in Chennai

    ReplyDelete
  5. This information really amazing thanks for share this article thank you..

    good morning shayari

    ReplyDelete
  6. The bright color makes it visible even from the high distance which is a plus point in case of emergency

    TOP 10 Best SOTs

    ReplyDelete
  7. Als je een partytent huurt is het belangrijk om ook aan de aankleding en inrichting te denken. Het is wel zo praktisch om dat ook bij Colors Events te regelen. Wij kunnen behalve jouw partytent ook zorgen voor meubilair zoals statafels, al dan niet voorzien van rokken, stoelen of gewone tafels. Ook feestverlichting mag niet ontbreken als je een feest in de avonduren organiseert

    Bezoek: colorsevents.nl

    ReplyDelete
  8. Webactueel schakel je in als je een maatwerk WordPress website laten maken wilt. Door een maatwerk website te ontwikkelen is het mogelijk om meer leads te genereren. Daarbij hebben we altijd oren voor de wensen en eisen die jij als ondernemer hebt als het om jouw website gaat. Bovendien gaat het om meer dan alleen een website. Ook het toepassen van de juist online marketingstrategie helpt hier in grote mate bij. Wij kunnen dit allemaal voor je verzorgen.

    Website laten maken

    ReplyDelete
  9. Webactueel schakel je in als je een maatwerk WordPress website laten maken wilt. Door een maatwerk website te ontwikkelen is het mogelijk om meer leads te genereren. Daarbij hebben we altijd oren voor de wensen en eisen die jij als ondernemer hebt als het om jouw website gaat. Bovendien gaat het om meer dan alleen een website. Ook het toepassen van de juist online marketingstrategie helpt hier in grote mate bij. Wij kunnen dit allemaal voor je verzorgen.
    Lees meer

    ReplyDelete
  10. Blogs are very Nice.The Information's provided in the Articles about Python are useful.keep updating and visit to know more about python
    python training in chennai | python training in annanagar | python training in omr | python training in porur | python training in tambaram | python training in velachery

    ReplyDelete
  11. Booty Calls Foxy Thunder Dating Most preferred trait Sexuality (red) Least preferred trait Charisma (Green) Facts Lovers Tip-friendly guests Masturbation Yes, ...
    qnnit

    ReplyDelete
  12. We understand that selling your home can be a difficult and confusing process, especially if you are in behind in your payments or have a home in need of repair. Our We Buy Houses investors can simplify the process by making you a clear, cash offer to purchase your home, along with presenting other options that may be available to you.
    We Buy Houses Glendale WI

    ReplyDelete
  13. pool cleaning service Get clean up your pool area with specialist clearing offerings business in an discount prices. Experienced understand how to fresh repair, matintenance and pool.

    pool cleaning companies

    ReplyDelete
  14. We understand that selling your home can be a difficult and confusing process, especially if you are in behind in your payments or have a home in need of repair. Our We Buy Houses investors can simplify the process by making you a clear, cash offer to purchase your home, along with presenting other options that may be available to you.

    We Buy Houses Brookfield WI

    ReplyDelete
  15. The Highest Grad And Best Quality Rated commercial Bounce Houses
    imp source

    ReplyDelete
  16. Bounce House Castle Inflatables and Party Event and Concessions Rentals. Reserve Online near South Milwaukee.
    great site

    ReplyDelete
  17. You guys will be greatful to know that our institution is conducting online CS executive classes and a free CSEET classes only for you guys. If anyone is interested then feel free to contact us or visit our website for more details https://uniqueacademyforcommerce.com/

    ReplyDelete
  18. fxchoice login Is More Than Just Another Forex Training Company. It Has A Financial Education Mission To Help People Worldwide Become Smarter Investors And Live Financially Independent Lives.

    ReplyDelete
  19. this is the one i am searching in google to read, if you wish to buy oud perfumes in dubai check our website. we are the best perfumes seller and manufacturer in UAE.

    ReplyDelete
  20. Don't Waste Your Time Checking USD TO INR FORECAST Every Day! Get The Most Accurate Exchange Rate For The USD TO INR FORECAST With Our Original Universal Currency Converter.

    ReplyDelete
  21. AximTrade Review Offers A Safe And Secure Platform To Do Forex Trading And CFDs And Our Customer Support Is Ready To Help You 24/7. You Can Easily Sign Up Your Aximtrade Login Account Here.

    ReplyDelete
  22. This comment has been removed by the author.

    ReplyDelete

  23. History UPSC Notes





    Indian polity UPSC


    UPSC coaching online is now possible. Here we provide
    online UPSC coaching for all General Studies paper. We
    also provide UPSC free materials with Mock test series.

    ReplyDelete
  24. best gynecologist in south delhi

    As an OB/GYN, you have the option of focusing only on women's health and giving birth, or you can practise both obstetrics and gynaecology in your clinic or hospital. Some OB/GYNs who also practise as general physicians provide care for all women, regardless of age.


    The two best ways to prepare for a career as an OB/GYN are to earn a four-year bachelor's degree and perform well on the MCAT (Medical College Admission Test). You may be more likely to be accepted into a medical school or residency programme if you have work experience in a hospital or clinic.

    ReplyDelete
  25. Top Five Customs Clearing Agents of Delhi

    If you're in the need of bicycle transportation services it is best to hire an organization that is certified and reliable. That way you are assured the bike you hire will reach the destination in a safe and timely manner. time.


    Another benefit of the use of transport services cut down on the cost of fuel and other expenses. If you own a vehicle and pay for gas, these costs can increase quickly. This gives you the chance to spend more cash on other activities, such as entertainment and recreational activities.

    ReplyDelete
  26. top pancreas specialist doctors in dwarka delhi

    The liver is a vital organ in the human body. It has more than 500 roles in your body. which include detoxification and the production of chemicals that aid in digestive digestion, the production of bile as well as the removal of cholesterol and bilirubin, and many more.
    If you've been diagnosed with liver issues, it is important to be taken care of promptly. There are numerous experts who can assist you in determining the best diagnosis and treatment for your condition.

    The first time you visit a hepatologist, it involves a thorough examination of your health history as well as blood work to identify the cause of your symptoms or other health issues. The doctor will need to know which medications you're taking and the dosages, as well as any changes to your diet you've implemented.

    Hepatobiliary surgery is a form of surgical treatment used to treat hepatocellular carcinoma (HCC), cirrhosis, and various liver disorders. In this procedure, tiny incisions are made along the abdomen, and a laparoscope can be used to reach the region.

    ReplyDelete
  27. Kundali Matching Service in Kurukshetra

    You've come to the right place now. Here are the top ten Indian astrologers that can assist you in making crucial life decisions.

    Our goal at Jyotish Punj is to connect the renowned Girami astrological gurus of Vedic astrology in India, in addition to bringing together the top astrologers in India. They have a solid astrological education and a strong reputation. You can now consult the best Indian gurus on Jyotish Punj from anywhere in the world.

    We offer you the best tarot readers, as well as the best numerology teacher and Jyotishacharya. so that you can receive answers to your questions from subject-matter experts at your convenience, without having to travel or wait

    ReplyDelete
  28. best dry needling therapist in gurgaon

    The physiotherapy profession is a recognized health care profession that includes assessment, evaluation and diagnosis, physical intervention, as well as the planning and the treatment of a range of disorders, diseases and disabilities in movement. It also includes manual therapy electrotherapeutic and exercise methods. It also incorporates education and patient-centered care. It is the most important way of rehabilitating from surgery and injuries.

    If you're in search of an establishment to help with back pain, neck pain or strains, a physiotherapy facility can assist you in relieving the symptoms and stop injuries from occurring again. Injury is a normal regular occurrence and occur every day such as slipping on a banana peel, or dropping something heavy onto your feet to quick jerks when driving on roads with potholes. But with the right rehabilitation, you'll return to regular routine in no time.

    ReplyDelete
  29. best psychiatrist in delhi

    We should consult a psychiatrist for an emergency psychiatric situation in Delhi to get a psychiatric hospital in Delhi. Unmanageable psychiatric patients in Delhi and hospitals for patients with psychiatric disorders

    Find the top rehabilitation facility in Delhi and a hospital for psychiatric patients to find the most effective medical professional for mental illness in Delhi. Consult a doctor about an emergency psychiatric situation in Delhi to get better care.

    ReplyDelete
  30. ivf doctors in south delhi

    If you're experiencing any issue with your gynaecology issues and you want to resolve it, consult one of the most reputable gynecologists within south delhi. Gynecologists will conduct an exams of the female organs and assist patients with regard to what options are they have available.


    Gynecologists possess a wealth of knowledge and experience in the treatment of issues pertaining to gynaecology, such as fibroids, polyps, and endometriosis. They are also proficient in the treatment of infertility.

    ReplyDelete
  31. brain tumor surgery in delhi

    A top physician to treat brain tumors in delhi Doctor. Sonal Gupta is highly skilled and a top doctor of spine in delhi and offers the complete treatment of brain tumors as well as keyhole spinal surgery. spinal decompression.

    Doctor. Sonal Gupta successfully performs the microsurgical treatment of brain tumors in Delhi using an intra-operative microscope. Find the top doctor to treat brain tumors within Delhi and the top specialist in spine surgery Delhi for micro-sized brain tumor surgery.

    ReplyDelete
  32. Chemotherapy Treatment for Lung Cancer in Delhi

    The developments in immunotherapy are creative in their own ways. The breakthrough that has made the most impact is the use of immune checkpoint inhibitors. This strategy targets the proteins that hinder the immune system's ability to respond.

    The use of medications like nivolumab and pembrolizumab has proven to be extremely effective in transforming it into an effective option. It has also been proven to be effective for advanced lung cancer, melanoma, and various malignancies.

    ReplyDelete
  33. Diabetes treatment in Janakpuri These are the leading causes of death in India. However, with the right treatment, care, and preventive measures, you can prevent coronary heart disease and thus live for longer.
    The best internal medicine doctor situated in Janakpuri is a highly competent doctor who completed her education at a top medical school located in the United States. She has been practicing for over two decades.

    She is renowned in the area. She has extensive knowledge of treating diseases that affect organs of the body and plenty of expertise in managing various diseases with ease. She has treated a range of patients in West Delhi with great success.

    ReplyDelete
  34. best breast cancer hospital in delhi

    Ductal carcinoma in situ (DCIS) is stage 0 (or non-invasive) breast cancer and has the best prognosis. There are 4 main stages of invasive breast cancer, stages I-IV (1-4). The lower the breast cancer stage, the better the prognosis tends to be.

    ReplyDelete
  35. dentist in Rohini Sector 8

    Dr. Seema Goyal, a top dentist in Rohini Sector 8, manages the best dental clinic in the area, providing a range of dental services.

    ReplyDelete
  36. uterine cancer surgery in gujarat

    Uterine cancer surgery in gujarat is when tumours start in the womb (uterus). It can happen before, during or after menopause. The most common type starts in the endometrium, which is the lining of the uterus. It can be caused by high levels of hormones, such as estrogen. It can also happen if you have abnormal vaginal bleeding or spotting between menstrual periods, or when you have a watery or blood-tinged discharge. The most common treatment for uterine cancer is surgery to remove the uterus and cervix. Your doctor may remove the ovaries and fallopian tubes too, which is called a total hysterectomy. Your doctor can also treat your uterine cancer with chemotherapy and radiation.

    ReplyDelete

Post a Comment

Popular posts from this blog

Twisted Klein: Non-Blocking Recipes

Non-Blocking Recipes Do you like expressjs , but don’t want to switch to Node.js? Want non-blocking execution in Python? Then look no further! Asynchronous execution is the very essence of what makes Klein a contender in todays web framework landscape. It’s also the most difficult concept to grasp since most Pythonistas are not accustomed to asynchronous programming. Hopefully with the addition asyncio to Python’s standard library, this will change. Klein is built atop Twisted and developers can expose Deferred objects for asynchronous behavior. A very brief overview will be given on Twisted Deferred , afterwards aspiring developers are encouraged to read the Twisted documents on the subject (provided in the links near the bottom). Deferred Overview To demonstrate how Deferred objects work, we will create a chain of callback functions that execute after a result is available. Don’t worry if this confuses you right now, the code will clear things up. from __future_

Simple self signed TLS server and client using Twisted

Self signed TLS server and client using Twisted Prerequisites openssl twisted & pyOpenSSL modules- pip install twisted[tls] treq module - pip install treq Basic knowledge of Twisted TCP servers/clients Generate self signed certificate Generate the server's private key using a secret, which is SuperSecretPassword in this case. openssl genrsa -aes256 -passout pass:SuperSecretPassword -out server.key 2048 Perform a CSR (certificate signing request). Ensure the FQDN (fully qualified domain name) matches the hostname of the server, otherwise the server won't be properly validated. openssl req -new -key server.key -passin pass:SuperSecretPassword -out server.csr # Common Name (e.g. server FQDN or YOUR name) []:localhost openssl x509 -req -passin pass:SuperSecretPassword -days 1024 -in server.csr -signkey server.key -out server.crt For development purposes, remove the password from the certificate. openssl rsa -in server.key -out server_no_pass.key -passin pas