How to select cell to run when using Jupyter when running it in VSCode? - python-3.x

I like the way Jupyter extension is built on VSCode, but I haven't get it to run a cell of my choise.
My question is: Is there a way to select which line gets executed or is it always the last in the file?
Right now I just put each output providing cell to separate file and import required features, but quick iterative experiments would be handy just to quickly write on the same file.

It looks like #%% begins a cell so there are two ways of doing this I think:
#%%
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
#%%
x = np.linspace(0, 20, 100)
plt.plot(x, np.sin(x))
plt.show()
and you can run each cell separately (or line - wherever you place the #%%) Run cell will pop up above the line you put this on.
Or install code-runner: code-runner. For more info see here: Jupyter-IPython and here Getting Started
EDIT: Just found another way from the last hyperlink:
Open a python file
Select a line or a block of code
From the command palette (cmd+shift+p) select the command Jupyter: Run selection/line
The results will be displayed on the right hand side
A status bar will appear with the name and status of the kernel

Related

python pyautogui module are not support bangla text

Here is my python code. I am trying to write something in Bangla text using pyautoGUI but unfortunately, it's not working.
import time
import pyautogui
time.sleep(2)
text = "হ্যালো,"
pyautogui.typewrite(text)
Pyautogui doesn't seem to allow some characters without giving a Unicode hex string but I found an easier way by putting it in your clipboard.
import pyautogui
import pyperclip
import time
time.sleep(5)
# Store our string to the clipboard
pyperclip.copy("হ্যালো")
# Hotkey the paste command
pyautogui.hotkey("ctrl", "v")
This works about the same as typewrite just using a paste command instead of sending it like a keyboard (one charachter at a time)
# Output to typed
হ্যালো

plotnine: UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail

I am trying to use plotnine to generate some graphs. I import the required libraries:
from plotnine import *
from plotnine.data import mpg
And then, if I run the following code in PyCharm I get a Warning message, the window plot
shows a "No answer" message and I am forced to restart the python terminal:
(ggplot(mpg) # defining what data to use
+ aes(x='class') # defining what variable to use
+ geom_bar(size=20) # defining the type of plot to use
)
<ggplot: (150517199824)>
C:\Users\alvaromc317\miniconda3\envs\general\lib\site-packages\plotnine\ggplot.py:363: UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail.
However, If I start a python terminal from windows cmd terminal and run the same script as before, I get no error message and I see the plot with no problem.
What is happening and how do I get to use plotnine in pycharm?
In case it is needed, I work using a Windows 10 machine and python 3x based on miniconda.
I'm having a similar problem, but on MacOS using the commercial addition of PyCharm.
From this github issue and this JetBrains issue, it looks like it might be related to a PyCharm bug.

iPython/ Jupyter notebook clear only one line of output

How can I print the status of a Jupyter notebook on the previous line? I think I'm looking for something like clear_output(), but for only a single line.
Sample code:
from IPython.display import clear_output
import time
print('This is important info!')
for i in range(100):
print('Processing BIG data file {}'.format(i))
time.sleep(0.1)
clear_output(wait=True)
if i == 50:
print('Something bad happened on run {}. This needs to be visible at the end!'.format(i))
print('Done.')
When this runs it gives the behavior of over-writing the previous status line, but both of the lines marked as important (with exclamation points and everything!) are lost. When this is finished the display just says:
Done.
What it should say is:
This is important info!
Something bad happened on run 50. This needs to be visible at the end!
Done.
This post suggests using clear_output() and then reprinting everything. This seems impractical because the amount of data I really tend to display is big (lots of graphs, dataframes, ...).
Here's two SO links about clear_output().
Is there a way to make this work that doesn't involve reprinting everything?
I got it woking using the update function of the display handle:
from IPython.display import display
from time import sleep
print('Test 1')
dh = display('Test2',display_id=True)
sleep(1)
dh.update('Test3')
This will do it:
import IPython
IPython.display.display_javascript(r'''
var el = document.querySelector('.output_text:last-of-type > pre');
el.innerHTML = el.innerHTML.replace(/(\n.*$)/gm,""); ''', raw=True)
This simple escape sequence trick can do the job most of the time. \n and \r can do a lot if used properly.
\r: (Carriage Return) (CR) returns the cursor to the beginning of the new line without moving to a new line.
\n:(Line Feed) (LF) moves the cursor to the next line.
import time
print('This is important info!')
for i in range(100):
print("\r"+'Processing BIG data file {}'.format(i),end="")
time.sleep(0.1)
if i == 50:
print("\r"+'Something bad happened on run {}. This needs to be visible at the end!'.format(i))
print("\r"+'Done.')

Making Python text green and using Spinning cursor - Newbies questions

I want to make my Python script file,when I "announce" something to the user, to be green like this:
How can this be done?I saw a script using this with sys.stdout.write but I dont understand how to use it, Im using a simple "print" commands..
Also, I would like to have the Spinning cursor spin as long as this command runs and only stops when this command stops(finishes):
print('running network scan')
output = subprocesss.check_output('nmap -sL 192.168.1.0/24',shell=True)
print('Done')
Any way to do that (unknown time until task is done)?
Im using a code suggested by nos here:
Spinning Cursor
So, about getting the terminal color to be green, there is a neat package called colorama that generally works great for me. To check whether the process is running or not, I would recommend using Popen instead of check_output, since the latter does not allow you to communicate with the process as far as I know. But you need to since you want to know if your subprocess is still running. Here is a little code example that should get you running:
import subprocess
import shlex
import time
import sys
import colorama
def spinning_cursor():
"""Spinner taken from http://stackoverflow.com/questions/4995733/how-to-create-a-spinning-command-line-cursor-using-python/4995896#4995896."""
while True:
for cursor in '|/-\\':
yield cursor
# Create spinner
spinner = spinning_cursor()
# Print and change color to green
print(colorama.Fore.GREEN + 'running network scan')
# Define command we want to run
cmd = 'your command goes here'
# Split args for POpen
args=shlex.split(cmd)
# Create subprocess
p = subprocess.Popen(args,stdout=subprocess.PIPE)
# Check if process is still running
while p.poll()==None:
# Print spinner
sys.stdout.write(spinner.next())
sys.stdout.flush()
sys.stdout.write('\b')
print('Done')
# Grab output
output=p.communicate()[0]
# Reset color (otherwise your terminal is green)
print(colorama.Style.RESET_ALL)

Python colorama not working with input?

Finally got colorama working today, and it works excellent when printing strings, but I got the common error everyone seems to get when I attempted to use colorama with input.
Here's my code:
launch = input(Fore.GREEN + "Launch attack?(Y/N): ")
Screenshot of output:
I had this same issue (Python 3.5.4) and, just in case it is not too obvious for somebody else looking at this, you can always rely on the workaround of combining print / input calls where you previously had just an input call:
print(Fore.GREEN + "Launch attack?(Y/N): ", end='')
launch = input()
This should produce the exact same output as in your question, with no extra blank lines and with the code coloring working without the need of importing anything else.
The (small?) disadvantage is that you you will end up with two lines of code where you previously had just one.
On my system, input() works with colors if you add
import sphinx.quickstart
to your module.
So here is the full code.
from colorama import Fore
import colorama
import sphinx.quickstart
colorama.init()
launch = input(Fore.GREEN + "Launch attack? (Y/N): ")
(This leads to two questions:
Why does it not work in the first place?
What is the actual reason? – Someone might like to dive into the sphinx source code.)
N.B. if you run python via winpty from Git Bash, set convert.
colorama.init(convert=True)
Otherwise, you do not get color with the current versions.
To get rid of this problem in the starting of the code add
import os
os.system('cls')
This will clear the screen and hence clear all the external factors blocking the colorama in input.
This works 100% you just need to do it once in the starting of the program [or just before the first use of colorama with input] and after that use colorama in any creative way you want to.
I hope this will help all the creative minds trying to make their codes more colourful
just make sure about the 'autoreset' in init()
init(autoreset=True)

Resources