Scrapy Shell: How to execute multiple lines of code in shell? - python

You will see in the screenshot that pressing enter after pasting a multiline code doesnt run it but merely send each time a "...".
How can I run this multiline pasted code?
someone asked here, but did not get (the right) answer;
Did not work:
Backspace
Use the arrow key to move the cursor, then use the delete key
Escape
F2

Pressing enter twice when inside the Python interpreter executes a block of code, but you have an unmatched open parenthesis on the last line, so you haven't completed defining the block of code. Also, I'm not sure what dic is in the last line, because you haven't included its definition, so you may need to fix that as well.

Running
a=[1,2]
for x in a:
print(x)
actually works (pressing 2 enters worked as expected). So I made a mistake in the code above. I aplogise, I should have checked that before.
I don't delete the question since the one on google can be confusing (the guy did not mentioned it was his mistake, so I though there was a trick to be found. The trick is to check the code).

you could use IPython link which simplifies the process, better yet you have access to every command line as if executed inside the shell.
The other alternative is to encapsulate this inside a function

I know this answer is a bit late, but someone will need the information sometime:
When you make a new line, i.e. title.quote.... you need to press the tab to create an indent, then it will work. Without indenting, you get the "expected an indent" error message.

Related

How to highlight text and paste in place with Python keyboard

I am trying to understand the behavior I am seeing from running my script below and how I can get my desired outcome. Basically I'm using keyboard.add_word_listener() to run a function when the string "test" is typed. It should select the tab trigger key plus the "test" text and then copy it, and then replace it with bbbb and then the copied text.
But if you look at the gif, it doesn't highlight the text. The "bbbb" gets inserted to the left of the "test" text. But it should have replaced the "test" text since it sends ctrl+shift+left which should select the previously entered text. The strange thing is the text still gets copied to the clipboard even though it doesn't look like it got selected. And for some reason it gets pasted in a separate line in the beginning. I don't understand how that is possible. It works on macOS but not Windows.
I also tried replacing ctrl+shift+left,ctrl+shift+left with shift+home but the result is the same.
The script:
import keyboard
import time
def test():
keyboard.send("ctrl+shift+left,ctrl+shift+left")
time.sleep(1)
keyboard.send("ctrl+c")
time.sleep(1)
keyboard.send("b,b,b,b")
time.sleep(1)
keyboard.send("ctrl+v")
keyboard.add_word_listener("test",test,['tab'],False,1)
keyboard.wait()
I've been scratching my head about why this doesn't work for a while now and I've found a way to make it work.
When you call keyboard.send that method parses the given hotkeys, and tries to send a scan_code for each key that you've specified.
It parses the keys via the keyboard.parse_hotkey method. If we call that method ourselves, we can see what codes we get back:
>>> keyboard.parse_hotkey("ctrl+shift+left")
(((29, 57373), (42, 54), (75,)),)
Here we can see that both ctrl and shift has two codes, each for their right/left counterparts.
As you've discovered as well as me, is if you try to call a hotkey like shift+home the button-combination seems to be working correctly, because your position on the document seems to change. However, it seems like the way (at least on my end) the system handles the calls to shift doesn't work when you call just one of the shift codes.
We can change the hotkey to include both of the codes by calling them individually in the hotkey:
>>> keyboard.parse_hotkey("ctrl+right shift+left shift+left")
(((29, 57373), (54,), (42,), (75,)),)
If we update your code, to include the above hotkey instead, we can see that the expected behavior is happening:
import keyboard
def test():
keyboard.send("ctrl+right shift+left shift+left")
keyboard.send("ctrl+c")
keyboard.send("b,b,b,b")
keyboard.send("ctrl+v")
keyboard.add_word_listener("test", test, ['tab'], False, 1)
keyboard.wait()
At the time of writing I don't really know exactly why the above code works while your original code doesn't.

Clearing Print in Python

So I'm pretty new to both coding and this website, so please bear with me if this is stupid:
I'm working on a personal project and would like to find a way to clear "print()" statements in python 3.6. For example:
print("The user would see this text.")
but if I continue
print("The user would see this text.")
print("They would also see this text.")
Is there a way to make it so a user would only see the second print statement?
I have seen "os.system('cls')" and "os.system('clear')" recommended, but I get these errors for each:
os.system('cls')
resulting in
sh: 1: cls: not found
and
os.system('clear')
resulting in
TERM environment variable not set.
Obviously I'm missing something, but if you know what it'd be much appreciated. If you know of another way to do what I'm thinking, that would also be awesome. Thank you for taking the time to read this, and thanks for any help.
Edit: I'm using Repl.it as my IDE. Could this be an issue with that site specifically?
Edit: Downloaded a new IDE to check, and the reply worked. If you are new and using Repl.it, be aware that some code does not function properly.
The method that I've used in the past to 'reprint' something on an existing line is to make use of the standard output directly, coupled with a carriage return to bring the printed statement's cursor back to the start of the line (\r = carriage return), instead of relying on the print function.
In pseudocode:
# Send what you want to print initially to standard output, with a carriage return appended to the front of it.
# Flush the contents of standard output.
# Send the second thing you want to print to standard output.
A working example in Python:
import sys
sys.stdout.write('\rThe user would see this text')
sys.stdout.flush()
sys.stdout.write('\rThe user would also see this text')
Edit
Figured I'd add an example where you can actually see the code working, since the working example above is going to execute so quickly that you'll never see the original line. The below code incorporates a sleep so that you can see it print the first line, wait, then reprint the line using the second string:
import sys
from time import sleep
sys.stdout.write('\rThe user would see this text')
sys.stdout.flush()
sleep(2)
sys.stdout.write('\rThe user would also see this text')

Python IDLE with Python 3.5.2 "crashing"

Okay, so let me just say beforehand: I am new to Python. I was just experimenting with IDLE and then I had this weird "crash". I put "crash" inside speech marks because I'm not sure if it qualifies as a crash, as rather than the program just crashing the way a normal program would in Windows, it still runs, but whenever I press enter and try and get it to accept new text it doesn't do anything. E.g. if you try and type "print('a')" and then hit enter it just goes to the next line (and doesn't print 'a'). I tried to make a simple function which converted an integer to a string where each character in the string was either a '1' or a '0', forming the binary number representing said (unsigned) integer.
>>> def int_to_str(int_in):
str_out=''
bit_val=1<<int_in.bit_length()
while(int_in>0):
if(int_in>bit_val):
str_out+='1'
int_in-=bit_val
else:
str_out+='0'
bit_val>>=1
return str_out
>>> print('a')
print('c')
Basically, it becomes completely unresponsive to my input, and allows me to edit/change "print('a')" even though I shouldn't be able to if it had actually "accepted" my input. Why is this? What have I done wrong/messed up?
Also, I made sure it isn't something else I was previously messing around with by closing the shell and opening it again and only putting in said code for the "int_to_string" function, and I haven't changed any settings or imported any modules before hand or anything like that (in case it matters).
EDIT: I tried reinstalling, and that helped a bit in that I can now do other stuff fine, but the moment I try to use the "str_to_int()" function, it has this same weird behaviour of not accepting/interpreting any more user input.
Your while loop never terminates, you need to re-arrange your logic. Printing variables can be an effective debugging tool - like this:
>>> def int_to_str(int_in):
str_out=''
bit_val=1<<int_in.bit_length()
while(int_in>0):
print(int_in, bit_val)
if(int_in>bit_val):
str_out+='1'
int_in-=bit_val
else:
str_out+='0'
bit_val>>=1
return str_out
If your program seems to be going on too long you can stop it with ctrl-c.

Program not showing returned values

I saw the code in an answer here, and I'm trying to pick it apart to see how it works. I think I understand it (using the or operator as a sort of ersatz "if" statement.), but that's not the issue here. It is supposed to return a value, and after visualizing the code(done here) it apparently IS returning a value. However, when I run it in the terminal, no values are ACTUALLY displayed. What is happening?
def ispalin(word):
return(not word) or (word[0]==word[-1] and ispalin(word[1:-1]))
ispalin(input("Enter a word."))
When this runs, it asks for a value, but nothing is displayed.
Unless you run code in the interpreter, Python will not just print return values in module-level code.
You need to explicitly print your result:
print(ispalin(input("Enter a word.")))
The interactive interpreter session is a REPL, or Read-Eval-Print loop, where it'll print the results of whatever you try, but when you run code from the command line or when doubleclicking on your script, no printing takes place.
That is because you are just returning the value and not printing it
print (ispalin(input("Enter a word.")))
Will print out your values
O/P after changing the sentence
Enter a word.malayalam
True
Try,
print ispalin(input("Enter a word."))

Why exactly is this error occurring when the loop executes to completion and how do I stop it?

Code: http://pastie.org/1966795
Trackback: http://pastie.org/1966799
TXT File I'm using: http://pastie.org/1966800
Keep in mind the program runs, my only issue is that it displays an error message at the end (see: trackback), that I don't know how to fix.
The problem happens when print_et_list is executing for the fourth time. By then you're past the end of your input file, so readline keeps returning empty strings. You should return from print_et_list early if question is blank, and correctly handle this case in main.
This is the piece of code that fixed it. I caught the error within the main function. It seems a bit choppy to me, but it runs. If anyone of you see this and have a more elegant solution, I'm all ears.
http://pastie.org/1969148
I use slang in my code to pique interest haha sorry if it offends. It's not NSFW, no worries.

Categories

Resources