pyperclip issues with PyCharm and batch files - python-3.x

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

Related

How determine Python script run from IDE or standalone

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.

Executable file made using Pyinstaller doesn't start

I want to convert the following sample python program into an executable file:
import os
print(os.getcwd())
To convert it into an executable I have used Pyinstaller:
pyinstaller app.py --onefile
And the EXE file is getting generated in the dist folder, but when I run it, it launches and immediately closes, and the expected print statement is not even displayed.
What could be the issue?
It does prints the statement, but just after printing it the code ends. You can add input() or use time.sleep(seconds) to make your program wait until you press a key or any particular number of seconds respectivly.
To check if your code(without the advice i have given) prints, start that python file in your command line.

How do imports work in Spyder IDE? Why is it different to running your code from Powershell?

I have seen a lot of questions on this topic, but None seem to explain why this is happening or provide a solution I can use.
The following script gives 8 different outputs depending on where it's run from and I really don't understand why. I've managed to pin down a pattern but still don't understand why this occurs and it hasn't helped me solve the problem.
I have a file called
__init__.py
In the same directory as this file, I have a folder called "source_code". In that folder I have another file called
__init__.py
The
source_code/__init__.py
file contains one line of code which is:
print("source_code imported")
The first
__init__.py
file has the following script:
import sys
print(sys.executable)
print(sys.path[0])
try:
from . import source_code
except ImportError as ie:
print(ie)
try:
import source_code
except ImportError as ie:
print(ie)
I am using Spyder 4.1.5 as part of the Anaconda package, as well as Powershell on Windows 10. I have a virtual environment, created with conda, with only Jupyter notebook and spider installed.
The pattern I have found (as far as I can tell) is as follows:
If I run the script through powershell, from outside the virtual environment, the output is as follows:
C:\Users\user\Desktop\Anaconda\python.exe
C:\Users\user\path\to\file
cannot import name 'source_code' from '__main__' (.\path\to\file\__init__.py)
source_code imported
if I run through Powershell from inside the virtual environment, the output is:
C:\Users\user\Desktop\Anaconda\envs\venv\python.exe
C:\Users\user\path\to\file
attempted relative import with no known parent package
source_code imported
if I open spyder, outside the virtual environment, and run the script by clicking into the editor and pressing "Control+Enter", the output is:
C:\Users\user\Desktop\Anaconda\python.exe
C:\Users\user\Desktop\Anaconda\python37.zip
cannot import name 'source_code' from '__main__' (C:\Users\user\path\to\file\__init__.py)
No module named 'source_code'
If (still in spyder, outside the virtual environment) I click on the run button in the bar at the top, the output is:
C:\Users\user\Desktop\Anaconda\python.exe
C:\Users\user\Desktop\Anaconda\python37.zip
cannot import name 'source_code' from '__main__' (C:\Users\user\path\to\file\__init__.py)
source_code imported
If I then click back into the editor and press "Control+Enter" again, the output is now:
C:\Users\user\Desktop\Anaconda\python.exe
C:\Users\user\Desktop\Anaconda\python37.zip
If I run spyder from inside the virtual environment. Click into the editor and press "Control+Enter", the output is:
C:\Users\user\Desktop\Anaconda\envs\venv\python.exe
C:\Users\user\Desktop\Anaconda\envs\venv\python38.zip
attempted relative import with no known parent package
No module named 'source_code'
Then click on the run button at the top, the output is:
C:\Users\user\Desktop\Anaconda\envs\venv\python.exe
C:\Users\user\Desktop\Anaconda\envs\venv\python38.zip
attempted relative import with no known parent package
source_code imported
Then clicking back into the editor and pressing "Control+Enter" again gives:
C:\Users\user\Desktop\Anaconda\envs\venv\python.exe
C:\Users\user\Desktop\Anaconda\envs\venv\python38.zip
attempted relative import with no known parent package
I have tried including "a=8" in the "source_code/init.py" file and using "from .source_code import a" instead of "from . import source_code".
I have also tried including the lines:
from pathlib import Path as path
sys.path.insert(0, path(__file__).parent)
This changed the output from print(sys.path[0]), but made no difference to the output of the import statements.
I would like to understand the following:
1: Why does
Cannot import name "source_code" from "__main__."
change to
"attempted relative import with no known parent package."
when I move from outside to inside the virtual environment?
2: Why does running the script from Powershell, add the location of the file to the beginning of sys.path, but running it from spyder does not? (see the difference in line 2 between outputs 1 and 2 vs outputs 3 onwards.)
3: In Spyder, what is the difference between clicking into the editor and pressing "Control + Enter" and clicking the Run button.
4: Why can't spyder find the "source_code" module (located in the same directory as the script) when I press "Control + Enter" but it can once I have run it by clicking the run button? (see the difference between output 3 vs output 5, and output 6 vs output 8).
5a: Why (once I have run the script by clicking the run button) does pressing "Control + Enter" stop generating an ImportError but also does not run the script (i.e. it doesn't print "source_code imported" in output 5 and 8).
5b: Why does this behaviour change depending on whether I'm inside or outside the virtual environment. i.e. Why is line 3 different in outputs 4 and 5, but the same in outputs 7 and 8?
6: How do I get my script to consistently, successfully import the "source_code" module, regardless of where I run it from?

How to create a Python Executable that can run other python-files stored in a folder?

Is it possible to create a Python Executable file (using PyInstaller or similar) that can in its code access other Python-files stored in a specific folder?
The reason for that it MUST be an Executable is that the script sometimes must be run from computers that has not it's own Python installed. I have no problem creating an executable (with PyInstaller for example) and they work fine. The python script itself loads various kinds of data into a database. But everytime there is a new kind of data that has to be loaded into the database I have to recreate the hole exe-file. I'm looking for a way for the executable to access python-files (with Data Load Instructions) so that the actual pyton load-files can be altered instead of the exe-file.
I have tried to find a solution using this:
import os, time
from subprocess import call
for file in os.listdir('.'):
if file == 'loadInstructions.py':
call(['python', file])
print(file)
cwd = os.getcwd()
print(cwd)
input('To EXIT progran press ENTER.')
time.sleep(3)
It works running it from a python editor but when I turn this into an exe-file it does not. If I creat an exe-file with "call(['python', file])" commented out the rest works which I interpret that the exe-file can find the file in question but not run it.
I would be gratefule for any help.

Python Import Module Not Working

I am very new to Python.
I am in command line and I typed the following:
python -m pip install -U pip
Python then starts working inside of command line.
When I type
import pyperclip
pyperclip.copy('testing')
pyperclip.paste()
'Hello World!'
is printed.
When I go to the python shell and type
import pyperclip
pyperclip.copy('testing')
pyperclip.paste()
I get an error message:
ModuleNotFoundError: No module named 'pyperclip'
How can I figure out where command line is looking when I type import pyperclip and where it is looking in the python shell to compare the two?
Edit #1:
import sys
sys.path
Seems to be important. I am guessing that when a module is imported, python checks one of those locations.
pyperclip-1.5.7 is now located in one of the paths specified., the "Lib" directory.
pyperclip-1.5.7 looks like this inside of the folder:
All of the other modules are located as ".py" files just outside of the pyperclip-1.5.7, maybe I need to move some stuff there. I wonder how I can tell python to check inside of this directory...
Edit #2:
I went to this location: https://leemendelowitz.github.io/blog/how-does-python-find-packages.html
On the page, the author writes:
So Python will find any packages that have been installed to those
locations.
Let's see if I can add something to the sys.path location that points to the specific package that is inside the pyperclip-1.5.7 directory and if that helps.
I have both python 3 and python 2 as well. The problem I faced was even after successful pyperclip installation it was not working in Python 3.
The solution I got was to move to the directory of installation of Python 2
C:\Python27\Lib\site-packages
and copied the folders
pyperclip
and
pyperclip-1.7.0-py2.7.egg-info
to the python 3 directory which was in my case
C:\Users\MYNAME\AppData\Local\Programs\Python\Python37-32\Lib\site-packages
I figured out what was wrong.
I also noticed that there are several posts all over in various locations of people reading the book
Automate the Boring Stuff with Python.
that are also struggling with this part.
After running
import sys
print('\n'.join(sys.path))
I started looking for differences between the output in command line and the output in the python shell. Everything looked extremely similar except in the directory:
lib/site-packages
I copied and pasted what was in this location, as pointed to in command line, to the location pointing to it in the python shell. I closed/reopened the shell and tried running the import pyperclip module, etc again and everything worked like a charm.
Problem is now solved.

Resources