Why does python script works differently in Spyder vs cmd prompt - python

I have the following script test.py:
import pathlib, os
path = "C:\\Windows"
pathparent = pathlib.Path("C:\\Windows").parent
if os.path.exists(pathparent):
print("path exists")
and when I execute it in Spyder IDE I get this:
path exists
when I run it from the command prompt (python test.py) I get this:
Traceback (most recent call last):
File "test.py", line 6, in <module>
if os.path.exists(pathparent):
File "C:\Anaconda3\lib\genericpath.py", line 19, in exists
os.stat(path)
TypeError: argument should be string, bytes or integer, not WindowsPath
Any idea why I get the different results?
Note: I know that wrapping pathparent in str() will make the if statement succeed, but what I want to know is why the the two environments yield different results.

os.path.exists() started accepting path objects in Python 3.6 and your problem is occuring in your cmd prompts as it is running Python 3.5, change it to 3.6 to fix your problem.

Related

Arbitrary strings in bash throw python errors?

Something in my setup of my shell causes arbitrary strings like "krmpfl" or "u45g5svtJ7" to create a Python error:
$> krmpfl
Traceback (most recent call last):
File "/usr/lib/command-not-found", line 28, in <module>
from CommandNotFound import CommandNotFound
File "/usr/lib/python3/dist-packages/CommandNotFound/CommandNotFound.py", line 19, in <module>
from CommandNotFound.db.db import SqliteDatabase
File "/usr/lib/python3/dist-packages/CommandNotFound/db/db.py", line 5, in <module>
import apt_pkg
ModuleNotFoundError: No module named 'apt_pkg'
I would expect bash (and not python!) to throw an error of the kind "Unknown command krmpfl. Did you mean...", but any non-recognized command is for some reason passed to python. I am confused.
Does anyone have an idea on how to debug this or how to move forward? I've tried type krmpfl but this (correctly) echoes bash: type: krmpfl: not found
My setup:
Win10 using Ubuntu 18.04 within WSL
ConEmu as a console
Bash-it
Python 3.8
Click (python package) installed to simplify creating commands
If your current shell function defines a function named command_not_found_handle, bash runs that for a non-existent command rather than immediately failing with a "command not found" error. In your case, that function exists and calls /usr/lib/command-not-found, which appears to be a Python script that tries to download (or at least suggest you download) a package with apt_pkg, but you don't have that Python module installed, which leads to the Python exception.

No Python IDE will start and it will not start in the Command Prompt

When I click on my Python IDE's (IDEL, PyScripter) they will not even open. I tried typing python in the command prompt and this is what happened:
C:\>python
Traceback (most recent call last):
File "C:\Python27\ArcGIS10.5\lib\site.py", line 548, in <module>
main()
File "C:\Python27\ArcGIS10.5\lib\site.py", line 537, in main
aliasmbcs()
File "C:\Python27\ArcGIS10.5\lib\site.py", line 469, in aliasmbcs
codecs.lookup(enc)
File "C:\Python27\ArcGIS10.5\lib\encodings\__init__.py", line 85, in search_function
norm_encoding = normalize_encoding(encoding)
File "C:\Python27\ArcGIS10.5\lib\encodings\__init__.py", line 57, in normalize_encoding`enter code here`
encoding = str(encoding, "ascii")
TypeError: str() takes at most 1 argument (2 given)
Did you recently install ArcGIS? It looks to me like ArcGIS installed a few libraries, and overwrote your site.py, but it's using code that's meant for Python3 rather than Python2.7. The str function is capable of taking in 2 arguments in Python3 but not in Python2.
To get your Python to work again, you could try deleting the entire ArcGIS10.5 directory from your computer (or temporarily moving it to your desktop and seeing if that helps). You can also try running python -S in Command Prompt to run Python without importing site.py.
To try to get ArcGIS working, you might be able to install Python3, and reinstall ArcGIS using that.
Hopefully that helps!

Running commands from Powershell

I am a beginner in Python and am learning via online tutorials. On Study Drill #6 for example 15 on this page, I'm trying to open up the 'ex15_sample.txt' file that I have created and exists.
This is what it says to do:
Start 'python' to start the Python shell, and use 'open' from the prompt just like in this program. Notice how you can open files and run 'read' on them from within 'python'?
In the command prompt, I entered python to start the Python shell and have tried typing in the following, which threw me an error:
open(ex15_sample.txt)
The error I get is:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'ex15_sample' is not defined
ex15_sample.txt is a file that exists in the same folder. How am I supposed to use open or any other command from the prompt? I am running Python 2.7.8 on Powershell, by the way.
The first argument of open is a string containing the filename.
Just put file name in Quotation Mark:
f = open('ex15_sample.txt')

'sleepymongoose' is not defined?

I am trying to set up sleepy.mongoose, a mongoDB REST interface using the instructions here.
I am using windows 8, :( ...anyway... I have python 3.3.2 installed and it is accessible from the cmd prompt. I also have pymongo installed, when i enter help('modules') to python, pymongo is on the list of available modules!
But when I try to run python httpd.py from the sleepy.mongoose dir (thanks karthikr), I get an error:
C:\Users\Brook\Desktop\sleepy.mongoose>python httpd.py
Traceback (most recent call last):
File "httpd.py", line 1, in <module>
sleepymongoose/httpd.py
NameError: name 'sleepymongoose' is not defined
Now I tried actually cding into the proper dir, but I get this other error:
C:\Users\Brook\Desktop\sleepy.mongoose\sleepymongoose>python httpd.py
File "httpd.py", line 221
print "\n================================="
^
SyntaxError: invalid syntax
I have had the same problem with Python 2.7 on Windows. Considering 'httpd.py' wich contains only:
sleepymongoose/httpd.py
You need this command line to start it:
python sleepymongoose/httpd.py
You are using python 3 to run python 2 code. The syntax for print amongst other things has changed. Use Python 2 or a server which supports python 3.

Unable to debug interactively with Python 2.7

I had asked a question previously on relative paths in python in SO question: How can I access relative paths in Python 2.7 when imported by different modules
The provided answer worked great in all of my scripts and functions. However, when trying to debug the files in IDLE (Python 2.7) it generates run time errors.
Can anyone point me to documentation on using the __file__ notation? Also I would like to understand why IDLE generates errors while running the sample code but running the same file from the command line or double clicking it (for the windows users) does not.
Any help would be greatly appreciated!
Note that I am running Python 2.7 on Windows XP with virtualenv (unactivated during these tests).
Sample Code
import os
import sys
curdir = os.path.dirname(__file__)
sys.path.append(curdir + '/..')
Error
Traceback (most recent call last):
File "C:\MyFile.py", line 3, in `<module>`
curdir = os.path.dirname(`__file__`)
NameError: name '`__file__`' is not defined
__file__ won't be set if you're writing this in the interpretor.
So:
>>> import os, sys
>>> curdir = os.path.dirname(__file__)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
Is expected.
__file__ is the name of the file that was called by the python interpretor - so if you ran this from a script it would work.
$ python curdir.py
$
(The script is exactly the same as what I put into the interpretor, hence no error or output)
From what I've observed using IDLE before, it acts as an interpretor - so it'll run the file in question. However, it wasn't started with that file, so the __file__ is never set.

Categories