How determine Python script run from IDE or standalone - python-3.x

I've recently started learning python and am still a newbie.
How can I determine if my code run from IDE or run standalone?
My code is not imported so
__name__ == "__main__" .
Someone suggested checking sys.executable name but I'm looking for a solution independent of the file name.
P.S: I create a standalone file with pyinstaller.

Here's a link to the page pyinstaller has on their site giving information about how to check the Run-Time information of your file: https://pyinstaller.org/en/stable/runtime-information.html
Basically it says to add the following code
import sys
if getattr(sys, 'frozen', False) and hasattr(sys, '_MEIPASS'):
print('running in a PyInstaller bundle')
else:
print('running in a normal Python process')
This should print the 'running in a PyInstaller bundle' message if it's all self contained and properly bundled, and it should print 'running in a normal Python process' if it's still running from your source code.

Related

pyperclip issues with PyCharm and batch files

I've been working through the book 'Automate the Boring Stuff With Python' and am doing the mclip chapter project, the code is fine, but I'm having issues with the execution.
the idea of the program is that it's a callable program from window's Run function, you should be able to type in run: mclip [keyphrase] which corresponds to a dictionary in the program that then copies to your computer's clipboard, a message that you can easily paste.
the issue arises that when I'm running the program through PyCharm, it runs fine, but I can't execute with a sys.args variable to fully run the program, and when I try and run it using windows run, and I include a sys.args variable keyphrase, the program returns an error saying I don't have the ability to import pyperclip when I have done that before already
I have edited the PATH variable of my machine to include everything python related in at least three different configurations, but I don't know why the windows run application cannot find pyperclip, as every time I go to install pyperclip with "pip install pyperclip" at all locations python could be, and all locations that are being referenced in PATH, I get a "you already have pyperclip installed" message
I don't know what to do, and there's not any questions that I've seen thus far that have been helpful.
#! python3
# mclip.py - A multi-clipboard program
import sys
import pyperclip
TEXT = {'agree': """Yes, I agree. That sounds fine to me.""",
'busy': """Sorry, can we do this later this week or next
week?""",
'upsell': """would you consider making this a monthly
donation?"""}
if len(sys.argv) < 2:
print('Usage: python mclip.py [keyphrase] - copy phrase text')
sys.exit()
keyphrase = sys.argv[1] # first command line arg is the keyphrase
if keyphrase in TEXT:
pyperclip.copy(TEXT[keyphrase])
print('Text for ' + keyphrase + ' copied to clipboard.')
else:
print('There is no text for ' + keyphrase)
Found out to import pyperclip or other libraries through PyCharm's terminal tab, this imports the library directly to the virtualenv that Pycharm is running as its interpreter

VS Code - issue with Python interpreter

All.
I'm trying use Python in VS Code. I've installed Python 3.7 and Python extension in VS Code. I've chosen correct interpreter, but when I tried run my script, it's still using Python 2.7.
I've wrote simple test script:
import sys
if __name__ == "__main__":
print(sys.path)
and I got:
'/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'
I've checked my VS code settings founded there python.pythonPath with value /usr/bin/python3.
I've added Python 3.6 to PATH.
I've read https://stackoverflow.com/a/55182584/11222097. None of the above methods worked.
I don't know what more I can do to make VS Code use the correct Python version.

Call a python script from another 'frozen' python script

I have a simple script that calls other scripts and works fine:
def demandesparbranche():
os.system('python Sources/x.py')
def demandesparlogiciel():
os.system('python Sources/xx.py')
def demandeshcapprouvees():
os.system('python Sources/xxx.py')
def challengesreussis():
os.system('python Sources/xxxx.py')
My idea was to add a GUI with tkinter and freeze this code (with pyinstaller) and use it as a set of buttons to launch the scripts that would in this way remain modifiable. I tried and it does not work, which is logical since in a computer without python installed the command 'python' is obviously unknown. The code works fine in my computer where python is installed.
Is this in any way possible using possibly another form of script calling? What I mean is: how to call the Python interpreter frozen by pyinstaller instead of a system one?
So, I found the solution:
Instead of calling the script with the 'os' module I imported the needed scripts :
from xscript import x
And called it directly via button:
tk.Button(mainframe, width=25, text="Something", command=x, bg='light grey')\
.grid(column=1, row=1, sticky=W)
2 caveats:
A file name init.py is needed in the same directory; same for the scripts imported.

Python3 interactive mode on Linux launches the codes twice

I have written a chess program in Python 3.4.3 and I am running the Python 3 interpreter in the interactive mode as follows:
python3 -i chess.py
However, the code after the class definitions get invoked twice and I do not know why. My code is on pastebin
You should remove the line from chess import * that is at the end of the file, it should not be needed.
Also, it is common to make sure that some of the code is not executed unless the code in the module is executed as a script.
if __name__ == '__main__':
# Not executed if the module is imported
g = Game()

cx_Freeze program created from python won't run

I am trying to create a .exe version of a python keylogger program that I found on the internet, so it can be run on Windows pc's without python installed.
The code for the program as is follows:
import pythoncom, pyHook, sys, logging
LOG_FILENAME = 'C:\\important\\file.txt'
def Key_Press(Char):
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,format='%(message)s')
if Char.Ascii==27:
logging.log(10,'ESC')
elif Char.Ascii==8:
logging.log(10,'BACKSPACE'
else:
logging.log(10,chr(Char.Ascii))
if chr(Char.Ascii)=='¬':
exit()
return True
hm=pyHook.HookManager()
hm.KeyDown=Key_Press
hm.HookKeyboard()
pythoncom.PumpMessages()
After the .exe file has been created using the build function of cx_Freeze, the following error occurs in a separate error box when I run the file:
Cannot import traceback module
Exception: cannot import name MAXREPEAT
Original Exception: cannot import name MAXREPEAT
I don't have much knowledge of cx_Freeze at all, and would very much appreciate any help, as even when I have tried using simple programs such as a hello_world.py program, the .exe file doesn't appear to work.

Resources