I'm using PyCharm 2018.1.4
If I write
from pathlib import Path
p = Path('.')
this runs fine.
On the other hand, if I write
import pathlib
p = Path('.')
I get
NameError: name 'Path' is not defined
I thought by using import pathlib I'm importing the complete library, including Path.
Compared to a terminal session:
$ bpython
bpython version 0.17.1 on top of Python 3.6.4 /Users/fanta4/anaconda3/bin/python
>>> import pathlib
>>> p = Path('.')
>>>
no problem.
And just python:
Nick-iMac:~ fanta4$ which python
/Users/fanta4/anaconda3/bin/python
Nick-iMac:~ fanta4$ python
Python 3.6.4 |Anaconda, Inc.| (default, Jan 16 2018, 12:04:33)
[GCC 4.2.1 Compatible Clang 4.0.1 (tags/RELEASE_401/final)] on darwin
>>> import pathlib
>>> p = Path('.')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Path' is not defined
Where is the problem in PyCharm?
In PyCharm I see python 3.6 (File > Default Settings > Project Interpreter)
Thanks!
If you do a naked import (i.e. import pathlib), the Path class is not in the local namespace of your script. It is an attribute of the module object pathlib. To successfully access Path in this case, you must explicitly refer to it via its parent object. I.e.: pathlib.Path.
Also, I'm not familiar with bpython, but what you've described in your terminal session does not occur in IPython. In fact, I consider it extremely poor design that importing a library in any interactive environment implicitly imports all of its children objects. Number one, it risks polluting the namespace. Number two, it causes confusion in both new and old users of a language.
Related
In my virtual environment on my debian machine, I am able to import numpy at the prompt But when I call it in a program it errors out.
I am looking over the net and they say to uninstall and re-install. I tried but novail.
Also, I am able to import it in python prompt but not when I call the script? Please help me out of this.
I am able to call successfully at the prompt:-
(venv) root#c3-redsuren-vm01:~/my-project# python
Python 3.8.2 (default, Apr 13 2020, 08:44:45)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import paramiko
>>> import numpy
>>> exit()
Here when I try to execute my program it errors out:-
(venv) root#c3-redsuren-vm01:~/my-project# ./test_nump.py
Traceback (most recent call last):
File "./test_nump.py", line 2, in <module>
import numpy
ImportError: No module named numpy
(venv) root#c3-redsuren-vm01:~/my-project# cat test_nump.py
#!/usr/bin/python
import numpy
print("test")
(venv) root#c3-redsuren-vm01:~/my-project#
As per request from the OP.
For any executable file, bash reads the first line with the shebang or #!... to extract the interpreter for the script. If it does not find the shebang, it will try to service the file type using the magic numbers and then use the relevant loading method. That's why running an ELF binary does not require you to specify the executor.
Now, virtual environments works by overriding your bash search path, i.e. when you type a command, where should it look. For example, if you have a binary name ls where should it find it to load from. It refers to your search path or the $PATH variable and scans the directories sequentially and stops at the first match. Virtual environment will prepend it's path to the $PATH when you do a source .venv. The source command simply tells your bash session to apply the bash directives from the .venv file.
In your source file, you have supplied the interpreter using the shebang directive to the global installation of python which does not have numpy in it's module list so it fails.
If you run it using python script.py, because the $PATH is overridden by virtual env, the shell will find the python version of virtual env first than the global one which has your numpy module.
Why does /usr/bin/env python work ? Because it's going to refer to your $PATH in your environment variable (which is modified by virtual env) and will find the correct python installation.
I have been using vs code and its data science module for a long time to create and edit python scripts via SSH. Recently I tried to open a jupyter notebook with it but I am having issues with the python interpreter
The python interpreter selected is the one from the base environment from miniconda
However, when I try to import a module that is installed on conda base I am getting
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-1-094d2d97d2ef> in <module>
1 # imports
2 import pandas as pd
----> 3 import matplotlib.pyplot as plt
ModuleNotFoundError: No module named 'matplotlib'
I am sure that matplotlib is installed on the base environment. If, on a terminal window, on VS code itself, I
open the same python interpreter (/home/user/miniconda3/bin/python)
call the same import (import matplotlib.pyplot as plt)
I get no error:
(base) user#Brightcore-testsrv:~$ which python
/home/user/miniconda3/bin/python
(base) user#Brightcore-testsrv:~$ /home/user/miniconda3/bin/python
Python 3.7.3 (default, Mar 27 2019, 22:11:17)
[GCC 7.3.0] :: Anaconda, Inc. on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import matplotlib.pyplot as plt
>>>
Your VS Code Jupyter notebook may be running with a different interpreter as its kernel. You can execute this code to check:
import sys
print(sys.executable)
If the result of running the code above is not /home/user/miniconda3/bin/python, you can use the kernel selector to switch kernels to your desired environment.
file words.py
def print_word():
print("Hello Words")
print(__name__)
When I run above code from console :
(base) C:\Users\Desktop\Python>python words.py
__main__
(base) C:\Users\Desktop\Python>python words.py
__main__
(base) C:\Users\Desktop\Python>python words.py
__main__
(base) C:\Users\Desktop\Python>python
Python 3.7.3 (default, Apr 24 2019, 15:29:51) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from words import *
words
>>> from words import *
>>>
Why during import it execute print only once but while running python words.py it execute print as many time as we execute ?
When you import a module, Python creates a module instance of that module.
After the first import, the interpreter already has an instance of that module therefore it doesn't execute anything
Python's import documentation: documentation
When a module is first imported, Python searches for the module and if found, it creates a module object, initializing it.
You can read more about the loading process of a module here :
If there is an existing module object with the given name in sys.modules, import will have already returned it.
The module will exist in sys.modules before the loader executes the module code. This is crucial because the module code may (directly or indirectly) import itself; adding it to sys.modules beforehand prevents unbounded recursion in the worst case and multiple loading in the best.
I have installed with pip several packages (numpy/pandas/blpapi/pyarrow). I work with a Windows 64-bit machine, python3.6 in a sublime environment.
While all packages are shown as correctly imported in the command prompt, some packages are not found by my sublime scripts.
To try and remedy this problem, I used sys.path.insert and changed the names of my scripts, to no avail. The traceback below describes what I'm seeing:
Code in Command Prompt:
>>> import pyarrow
>>> import pandas
>>>
Code in Sublime (better_name.py):
print('Hi')
import numpy
import pandas
Output of better_name.py:
Hi
Traceback (most recent call last):
File "C:\Users\Documents\better_name.py", line 4, in <module>
import pandas
ModuleNotFoundError: No module named 'pandas'
Obtaining the paths in Command Prompt:
>>> import os
>>> import numpy
>>> path = os.path.dirname(numpy.__file__)
>>> print(path)
C:\Users\AppData\Local\Programs\Python\Python36\lib\site-packages\numpy
>>> import pandas
>>> path = os.path.dirname(pandas.__file__)
>>> print(path)
C:\Users\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas
Trying to use sys.path.insert :
print('Hi')
import sys
import numpy
import os
sys.path.insert(1, r"C:\Users\AppData\Local\Programs\Python\Python36\lib\site-packages\pandas")
Output:
C:\Users\Documents>better_name.py
Hi
Traceback (most recent call last):
File "C:\Users\Documents\better_name.py", line 7, in <module>
import pandas
ModuleNotFoundError: No module named 'pandas'
I get the same results whether I change the argument in sys.path.insert to 0.
The issue seems to be that your default version of python points to the 32-bit version - i.e. when you say python your windows system executes the 32 bit version.
One workaround is to specify the full path of your 64 bit version - i.e. launch your script as
C:\PATH\TO\64-BIT-VERSION\PYTHON.EXE your_script.py
from the command line.
The other option is to set your windows environment variables to point to the 64 bit version by default. This link should help
I have python 2.7.12 installed in Ubuntu 16.04 (64-bit version). I have modules such as numpy, scipy, sympy etc. installed via pip as well. My problem is, when I open python command line via Terminal and try to import these modules, I get the following error:
$ python
Python 2.7.12 (default, Jul 10 2016, 20:42:07)
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named numpy
>>>
Upon doing some research, I found from this thread that if I open python command line using /usr/bin/python and try importing these modules, I don't get any errors.
$ /usr/bin/python
Python 2.7.11+ (default, Apr 17 2016, 14:00:29)
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> import scipy
>>> import sympy
>>> import matplotlib
>>> import pandas
>>>
But I would like to know if there is any way I can just type in python from Terminal and import these modules in the python command line? For example, if I write a program like this,
x = 2
print x
y = 5
print y
print x+y
import numpy
import scipy
import sympy
save it in a file named test.py in my desktop and open it using the command /usr/bin/python test.py, I am getting the desired output.
$ /usr/bin/python test.py
2
5
7
But if I try the same with the command python test.py, I get the error again
$ python test.py
2
5
7
Traceback (most recent call last):
File "test.py", line 8, in <module>
import numpy
ImportError: No module named numpy
From what I understand, python doesn't have access to system wide modules since it is installed locally. If so, is there a way to make python global or the modules local to python? I have been trying for the past couple of hours to find a solution but I haven't found anything yet and I am new to Linux. Thanks for your help.
I think the root cause is you have several python binary under $PATH, and your system doesn't use /usr/bin/python by default.
run command which python to see which python is used by default
rename the default python file to something like 'python-2-7-12'
then try to run python test.py again to see if it is resolved.