Some Python scripts CMD windows closes immediately - python

Some of my python (3.6) scripts will close immediately when run. Others, however, do not. The script in question will copy a selected text and look up the word on dictionary.com. When I run the script from Pycharm, it works as intended. However, when I run it from the search bar or double-click the file from within the folder, it immediately closes. I have tried using input("something") and time.sleep(1) but with no luck. I also have success with opening a command window and typing python dictionary.py and enter.
This is what the body looks like:
import pyperclip
import keyboard
import pyautogui
import time
def lookup():
prev = pyperclip.paste()
time.sleep(.1)
pyautogui.hotkey('ctrl', 'c')
time.sleep(.1)
word = pyperclip.paste()
url = f"https://www.dictionary.com/browse/{word}?s=t"
webbrowser.open(url)
pyperclip.copy(prev)
def switch_back():
pyautogui.keyDown('ctrl')
pyautogui.press("w")
pyautogui.keyUp('ctrl')
pyautogui.keyDown('alt')
pyautogui.press('tab')
pyautogui.keyUp('alt')
print("Welcome to dictionary lookup!")
print("Press F2 to lookup a word on www.dictionary.com")
word = ""
keyboard.add_hotkey('f2', lookup)
keyboard.add_hotkey('f1', switch_back)
while word is not "stop":
pass
Some of my other scripts that ask for input will not close immediately. The one I tried does not use any imports, so I'm theorizing this might have something to do with it. The reason I want this is that I want to be able to press windows button, type name of script and press enter. Rather than to find the folder, open a command window and type the whole thing out.

It seems the problem has been resolved. A time ago I tried installing a newer version of python (3.8). I have not been using this version (because I could not figure out how to change the python interpreter in Pycharm). I tried uninstalling it, and it seems to be working now.

Related

I can't get my code to run through and IDE but I can through IDLE (Python 3)

So I'm still super new to coding and I was trying to setup some automation. Since I'm still new to it I was just going to have my mouse to the icons and stuff and click when it gets to it's location and I was gonna make it better over time. Anyway whenever I run it via double click or Sublime it won't run however it will run through IDLE. It will print the first few things but doesn't do anything after I enter an input. It does just fine through IDLE. Both Sublime and IDLE don't say any errors.
import keyboard
res = pyautogui.size()
point = pyautogui.position()
print('Your screen resolution is ' + str(res))
print('Mouse Location is ' + str(point))
auto = input('Please enter automation command:')
if auto == 'Gmail':
pyautogui.moveTo(661, 1079, duration=.1)
else:
print('Currently Not Supported')
Sublime is a text editor, and needs to be set up properly.
Try this: open Command Prompt then navigate to the folder where your script is.
type python script_name.py and see if it runs.
if it runs, then your python installation is ok, you just need to set up Sublime. check this: https://www.youtube.com/watch?v=xFciV6Ew5r4

Trying to run a python script from a batch file without the cmd window popping up

I'm trying to create a program that takes your highlighted text then inverses the case of it using a python script.
The logic is essentially: get highlighted text into clipboard, do the transformation, then return the text to the clipboard and paste it.
I'm trying to execute this by creating a batch file that runs from an AutoHotKey hotkey, but the thing is the batch file has to run without popping up the cmd window because then it changes the window focus and it can't properly get the highlighted text.
The code works when I run it inside of PyCharm, and I can get the file to run from the hotkey, but the window still pops very briefly thus ruining the process.
The course I'm going through said to put #pyw instead of #py at in the batch file to make it run through python windowless, but still the window pops up very briefly. I can't seem to find a solution that works.
I tried to run it through a .vbs file but that didn't work the way I wanted it to. I checked to make sure pythonw.exe is working, and it is. I tried to change the file name to .pyw in the batch code.
What am I doing wrong? Is it with my python code, or my batch code? I don't know.
My Batch Code:
#pyw "C:\Users\offic\PycharmProjects\test\automate the boring stuff\projects\change case of selected.pyw" %*
My Python Code:
#! python 3
import pyperclip
import pyautogui as pya
import time
import sys
#mystery code I tried to make work as a solution
# import ctypes
# import os
# import pywin32_system32
#
# hwnd = ctypes.windll.kernel32.GetConsoleWindow()
# if hwnd != 0:
# ctypes.windll.user32.ShowWindow(hwnd, 0)
# ctypes.windll.kernel32.CloseHandle(hwnd)
# _, pid = pywin32.GetWindowThreadProcessId(hwnd)
# os.system('taskkill /PID ' + str(pid) + ' /f')
def copy_clipboard():
pyperclip.copy("") # <- This prevents last copy replacing current copy of null.
pya.hotkey('ctrl', 'c')
time.sleep(.01) # ctrl-c is usually very fast but your program may execute faster
return pyperclip.paste()
clipboard = copy_clipboard()
try: #check if there is an argument
# convert clipboard to uppercase if arg is 'u'
if sys.argv[1] is 'u':
pyperclip.copy(clipboard.upper())
# convert clipboard to lowercase if arg is 'l'
elif sys.argv[1] is 'l':
pyperclip.copy(clipboard.lower())
#else just swap the case of every character if the arg is not u or l
else:
pyperclip.copy(clipboard.swapcase())
#if there are no args just swap the case of every charater
except:
# put swapped string to clipboard
pyperclip.copy(clipboard.swapcase())
pya.hotkey('ctrl', 'v')
# hELLO
My AutoHotKey Code (if this somehow matters):
^+q::
Run, "C:\Users\offic\Documents\MY BATCH FILES\swapcase.bat"
return
^+q::
Run, "C:\Users\offic\Documents\MY BATCH FILES\swapcase.bat",, Hide
return
AutoHotkey Run Options: Hide.
It would be the running of swapcase.bat causing the console window to show. Doubt it is pyw running pythonw.exe as both being Graphical User Interfaces (GUI) instead of a Console User Interface (CUI) that cmd.exe is, as it interprets swapcase.bat.
You can run your Python script (with .pyw extension) from AHK:
Run script.pyw, c:\mydir
c:\mydir is the location of the Python script.
This will work if Python is associated with .pyw extension of course.

Creating a hotkey to enter text using python, running in background waiting for key-press

I'm trying to emulate the copy/paste functionality of my OS using a python application.
What I want to have happen is that when I press the keys, say, "Alt-X", it would paste predefined text into the currently occupied text field. Basically copy and paste but creating my own.
I've tried using pyautogui and other frameworks but I can't seem to figure out how get it to wait for key-press in the background, and then enter the text after that.
Any ideas? Thanks.
Try keyboard library :
import keyboard
text_to_print='default_predefined_text'
shortcut = 'alt+x' #define your hot-key
print('Hotkey set as:', shortcut)
def on_triggered(): #define your function to be executed on hot-key press
print(text_to_print)
#write_to_textfield(text_to_print) #<-- your function
keyboard.add_hotkey(shortcut, on_triggered) #<-- attach the function to hot-key
print("Press ESC to stop.")
keyboard.wait('esc')
the above will print a predefined text into the terminal.
execute the script with sudo i.e. sudo python program_name.py
installation :
sudo pip install keyboard
Note : According to documentation 'Works with Windows and Linux (requires sudo), with experimental OS X support'

Anyway of clearing text in IDLE

Is there anyway of clearing text in IDLE, its really anoying when i run the script a couple of times and then there's a cluster of words which is really hard to read.
and yes I have looked on google, stack_overflow and a couple of more websites but i cant find anything useful.
I tried to do:
import os
def cls():
os.system("cls")
>>>cls()
If you mean using the actual IDLE shell, I don't think there's any way to do it. IDLE is not meant to run programs from, it's just supposed to be a development tool. If you want to run programs from terminal or cmd, you can clear the text easily.
Use this instead:
os.system("clear") # or "cls" on windows
or
subprocess.call('clear') # or "cls" on windows
To fake it in IDLE, you can use something like:
print("\n" * 50)
from subprocess import call as c
def cls():
c("cls",shell=True)
print([x for x in range(10000)])
cls()
Whenever you wish to clear console call the function cls, but note that this function will clear the screen in Windows only if you are running Python Script using cmd prompt, it will not clear the buffer if you running by IDLE.

How to stop command prompt from closing in python?

I am very new to python.. I used the code
x = input(" Hey what is your name " )
print(" Hey, " + x)
input(" press close to exit ")
Because i have looked for this problem on internet and came to know that you have to put some dummy input line at the end to stop the command prompt from getting closed but m still facing the problem.. pls Help
I am using python 3.3
On windows, it's the CMD console that closes, because the Python process exists at the end.
To prevent this, open the console first, then use the command line to run your script. Do this by right-clicking on the folder that contains the script, select Open console here and typing in python scriptname.py in the console.
The alternative is, as you've found out, to postpone the script ending by adding a input() call at the end. This allows the user of the script to choose when the script ends and the console closes.
That can be done with os module. Following is the simple code :
import os
os.system("pause")
This will generate a pause and will ask user to press any key to continue.
[edit: The above method works well for windows os. It seems to give problem with mac (as pointed by ihue, in comments). The thing is that "os" library is operating system specific and some commands might not work with one operating system like they work in another one.]
For Windows Environments:
If you don't want to go to the command prompt (or work in an environment where command prompt is restricted), I think the following solution is gooThe solution I use is to create a bat file.
Use notepad to create a text file. In the file the contents will look something like:
my_python_program.py
pause
Then save the file as "my_python_program.bat" - DO NOT FORGET TO SELECT "All Files!
When you run the bat file it will run the python program and pause at the end to allow you to read the output. Then if you press any key it will close the window.
Just Add Simple input At The End Of Your Program it Worked For Me
input()
Try it And It Will Work Correctly
Try this,
import sys
status='idlelib' in sys.modules
# Put this segment at the end of code
if status==False:
input()
This will only stop console window, not the IDLE.

Categories