To start, am incredibly new to python so please bear with me.
I want to write a very simple script to demonstrate some operations with the list data type. This is an abridged version of my script (It's named listTest.py)
#!/usr/bin/python
import sys
print(sys.version_info)
print “successful start”
print “ “
listAl = [ a, b, c, d, e, f, g]
listNu = [ 1, 2, 3, 4, 5, 6]
print listAl
print listNu
To run it, I open op my terminal with spotlight search on my mac (macOS 10.12.6) and type in
python
which runs python 2.7.10. I also have python 3.5.1 which I know I can run with
python3
With my python 2.7.10 prompt open I type the following (left the python starting entry for complete transparency)
Python 2.7.10 (default, Feb 7 2017, 00:08:15)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> listTest.py
and get the following message:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'listTest' is not defined
>>>
Now, I have no clue what to do at this point. At first I was concerned that I hadn't installed python properly (which I hadn't since python 2.7.10 came with this OS by default) so I checked that I had all my essential components to python. I was missing pip, so I installed pip (here is the pip and python directories)
/usr/local/bin/pip
/usr/bin/python
Then I was concerned I had my listTest.py text file (UTF-8 encoding) in the wrong directory, so I checked it's location on my computer, by typing
ls Desktop
yep, it's there,(which I think is alright?) along with some other text files that crashed and burned in the same way. I also tried installing a virtual environment (pyvenv) to run the script in hoping it would mitigate the issue but I got the same exact error.
What can I try now? Thank you in advance for being patient.
Python has two basic modes: script and interactive. The normal mode is the mode where the scripted and finished .py files are run in the Python interpreter. Interactive mode is a command line shell which gives immediate feedback for each statement, while running previously fed statements in active memory.
You can run python in interactive mode with entering command python or python3.
When you have a file that you want to run you should pass the file address as an argument to command like:
python listTest.py
or
python3 listTest.py
If you are getting "can't open file 'listTest.py': [Errno 2] No such file or directory" error It's because you are in the wrong place!
open the folder in your File Explorer then from the address bar copy the address and try to change directory to the directory that your files exists in:
cd Directory_That_ListPy_Is_In
python ListTest.Py
Here is some tutorial that helps you master the terminal navigating files and folders.
Copy the whole program and paste it in shell(begginer method),It will/should look like this:
Python 2.7.10 (default, Feb 7 2017, 00:08:15)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>#!/usr/bin/python
>import sys
>print(sys.version_info)
>print “successful start”
>print “ “
>listAl = [ a, b, c, d, e, f, g]
>listNu = [ 1, 2, 3, 4, 5, 6]
>print listAl
>print listNu
IT WILL SPLIT IN LINES AND REFORMAT ITSELF.
This will execute program line by line...
Related
I'm a beginner in Python. I tried to resolve this error but I couldn't. This code worked before but not anymore. I run the code in PyCharm and getting this error:
Traceback (most recent call last):
File "C:/Users/MJavad/Desktop/test.py", line 3, in <module>
b = float(sys.argv[1])
IndexError: list index out of range
I ran CMD and had also an error:
File "<stdin>", line 1
python test.py 1 2
^
SyntaxError: invalid syntax
Can anyone help, please? This is my code:
import sys
import math
b = float(sys.argv[1])
c = float(sys.argv[2])
f = b * b - 4.0 * c
d = math.sqrt(f)
print((-b + d) / 2.0)
print((-b - d) / 2.0)
and this is the code and error in PyCharm:
It seems that there is confusion about how Python code can be executed and processed.
On the one hand, there is the Python interpreter in the interactive mode. This is usually started with the command python (without arguments) and then you have the possibility to execute Python code directly in an interactive Python specific shell. This distinguishes Python from other languages that need to be compiled first to execute code. Further information are available in the official Python tutorial.
On the other hand, Python can also be executed in such a way that not the interpreter with an interactive shell is started, but a file is read and processed. This is usually done with the command python together with the path to the Python file as argument, e.g. python test.py. See also the documentation about using Python.
With this knowledge the problems that have happened to you can now be explained and solved:
If you are simply starting the Python interpreter in interactive mode (without any further arguments), you don't have access to the command line arguments any more, for example:
$ python3.8 # or whatever your command is, maybe only python or python3
Python 3.8.0 (default, Oct 28 2019, 16:14:01)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys; sys.argv
['']
As you can see, there isn't really a usable information in argv. And that is your problem: The arguments aren't successfully loaded into sys.argv. So an index error happened, because the arguments are simply missing:
$ python3.8
Python 3.8.0 (default, Oct 28 2019, 16:14:01)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.argv[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
The only difference to your example is that you have already provided the path to the script, because it's File "C:/Users/MJavad/Desktop/test.py", line 3, in <module> instead of File "<stdin>", line 1, in <module>. So you have started the program via python test.py, but also without any further arguments which would be loaded into sys.argv in the program, see:
$ python3.8 test.py
Traceback (most recent call last):
File "test.py", line 3, in <module>
b = float(sys.argv[1])
IndexError: list index out of range
Your sys.argv now looks like this: ['test.py'], but still no index positions 1 and 2 available. So you have to invoke python also with additional arguments which will be passed into sys.argv:
$ python3.8 test.py 1 2
Traceback (most recent call last):
File "test.py", line 6, in <module>
d = math.sqrt(f)
ValueError: math domain error
And it worked! Ok, you have another exception, but it's in line 6 and every line before was successfully processed, also the command line arguments. Now you can proceed to debug your program, i.e. start programming or trying other parameters than 1 and 2 etc.
So that's the theory. Since you're also using PyCharm and have the "Terminal", the "Run configuration" and a "Python Console" available, things get a bit more complicated:
The "Terminal" should have a prompt available if you start one. This prompt shouldn't be a prompt from the Python interpreter (normally prefixed by >>>). It should be a terminal prompt (normally prefixed by an $ at the end), where you can also start a python interpreter in interactive mode or start a python program as described above. This "Terminal" is a terminal emulator given you by PyCharm and can also do other things for you, not only starting python programs. See the PyCharm documentation for more information.
The "Python Console" is a similar Python interpreter you also can get if starting python from the "Terminal". But then, you already started the interactive mode of the interpreter and there are no possibilities to pass command line arguments (maybe somewhere, but not as default). See the PyCharm documentation for more information.
If you're using an IDE like PyCharm, you should normally start the program as recommended by the IDE. In this case, you're writing a file and start the file neither by running the "Terminal", nor going into an interactive Python shell. Instead of this, you have to configure the IDE "Run" as described in the PyCharm documentation or as you can see here:
This is just the GUI way of calling python C:/Users/MJavad/Desktop/test.py 1 2 directly inside PyCharm.
So I would recommend that you're only starting your programs via option 3 (via "Run" configuration or "DEBUG" configuration). You only have to pay attention, running the right configuration (see if the path is the correct one and the parameters are right).
It is not normal to have a Python prompt (>>>) directly after starting a "Terminal", though. And inside interactive mode of Python's interpreter, you simply cannot start a python script, because you're already in a python interpreter, for example:
$ python3.8
Python 3.8.0 (default, Oct 28 2019, 16:14:01)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> python test.py 1 2
File "<stdin>", line 1
python test.py 1 2
^
SyntaxError: invalid syntax
I should also mention that you can pass arguments into python interactive mode, for example (the - stands for <stdin>):
$ python3.8 - hello world
Python 3.8.0 (default, Oct 28 2019, 16:14:01)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys; sys.argv
['-', 'hello', 'world']
>>>
A simple check if the Dropbox API works, I have below dropbox.py script created
import dropbox
dbx = dropbox.Dropbox('MY_TOKEN')
dbx.users_get_current_account()
Running it in normal script mode using terminal, I have to use below command.
username$ python3 dropbox.py
This returns below error:
Traceback (most recent call last):
File "dropbox.py", line 1, in <module>
import dropbox
It works okay when using the interactive mode with below command
username$ python3
Python 3.6.4 (default, Jan 6 2018, 11:51:15)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dropbox
>>> dbx = dropbox.Dropbox('MY_TOKEN')
>>> dbx.users_get_current_account()
FullAccount displayed here successfully
Why is there a difference in interactive versus script mode? How to get the script mode working?
Probably, the issue is name clutch between your file dropbox.py and module.
When running dropbox.Dropbox, python tries to create instance of Dropbox class from your file (which is treated as module too), and you have no such.
The motivation behind this order of imports is ability to "override" pre-installed modules with your own.
TL;DR: renaming your file should help.
Pythonproject directory structure is like
--test
--upperlevel
-- __init__.py
-- manager.py
-- UpperLevel.py
this files in turn contains
# __init__.py
msg = "YAYY printing !!!"
print msg
# UpperLevel.py
from upperlevel import msg
# manager.py
import UpperLevel
So in my local MAC book with python 2.7.10, started a python shell in test directory.
From that shell,
Python 2.7.10 (default, Jul 30 2016, 19:40:32)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import upperlevel.manager
YAYY printing !!!
>>>
it worked !!!!
However i started a virtual machine (ubuntu 14.04 and python 2.7.10) with vagrant and added same test directory to it.
so if i did the same thing
Python 2.7.10 (default, Jul 13 2017, 19:26:24)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import upperlevel.manager
YAYY printing !!!
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "upperlevel/manager.py", line 1, in <module>
import UpperLevel
File "upperlevel/UpperLevel.py", line 1, in <module>
from upperlevel import msg
File "upperlevel/upperlevel.py", line 1, in <module>
from upperlevel import msg
ImportError: cannot import name msg
>>>
So my questions are
1) why it is not working in the later case, i tried the same in docker and getting the same error
2) there is no such file in my project, File "upperlevel/upperlevel.py", line 1, in
3) why it is searching for upperlevel.py instead of UpperLevel.py
FYI
It looks like if we do "import upperlevel" from UpperLevel.py it is refering back to itself instead of going to upperlevel/init.py.
UPDATE:
I understood where the problem is from.... my test directory(volume) is being shared between mac and vagrant/docker, somehow UpperLevel.pyc is being treated as upperlevel.pyc in that shared volume.
Instead of running in a shared directory i created same folders/files in /home/vagrant and it worked.
It seems you are running from a Mac environment, and it is possible that the Python default search paths are different for those builds, despite the version being similar.
Try comparing:
import sys
print(sys.path)
It is probable that the default installation search paths might differ.
You can use the environment variable $PYTHONPATH to add additional import paths, while I don't really like this method it can be sufficient in most cases.
You can also setup your package in a proper module installation path.
Finally answering my own question...the problem is mac has a case insensitive file system and when it is mounted on linux, python is trying to use ubuntu mode of module reading like in the case sensitive way on a case insensitive File system.
After a lot of research found this link for docker https://github.com/docker/for-mac/issues/320 so those when using ubuntu docker with python on a mac be careful with your naming conventions.
OK so for school I am having to set up a computer using Ubuntu 12.04 to run Python programs written in Python 3.3. I was aware that 12.04 came with Python 3.2, so I followed the procedure in the first reply in this thread to install Python 3.3:
Now when I open the Terminal, I type ~/bin/py to get it to display the following at the top of the terminal:
Python 3.3.2 (default, Dec 10 2013, 11:35:01)
[GCC 4.6.3] on Linux
Type "help", "copyright", "credits", or "license" for more information.
>>>
So far so good. Now I am having trouble replicating the functionality of the same Python program that I execute as follows on my Windows laptop.
(This is what I type in the Python commandline on windows)
import filereader
from filereader import *
reader = filereader("C:\Python33\ab1copy.ab1")
reader.show_entries()
The end result is a directory of data types found in the file. The filereader class is located in Python33\Lib\site-packages\filereader.py in the above example. On the Ubuntu computer its location is Python-3.3.2\Lib\site-packages\filereader.py. Also on Ubuntu, the ab1copy.ab1 file is located in the home directory for now.
After I achieve the recognition of Python 3.3.2 in the Ubuntu Terminal as noted above, how can I replicate my program's functionality there? If I try to put in the same first command "import filereader" I get the following error:
>>>import filereader
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'filereader'
try this in the terminal
python3 your_file.py
It's probably not in your python path.
Check this to see where it looks for your source:
import sys
print(sys.path)
I've recently given up on macports and gone to homebrew. I'm trying to be able to import numpy and scipy. I seem to have installed everything correctly, but when I type python in terminal, it seems to run the default mac python.
I'm on OSX 10.8.4
I followed this post: python homebrew by default
and tried to move the homebrew directory to the front of my %PATH by entering
export PATH=/usr/local/bin:/usr/local/sbin:~/bin:$PATH
then "echo $PATH" returns
/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/opt/local/bin:/opt/local/sbin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/opt/X11/bin
however when I look for where my python is by "which python", I get
/usr/bin/python
For some reason when I import numpy in interpreter it works but not so for scipy.
Python 2.7.2 (default, Oct 11 2012, 20:14:37)
[GCC 4.2.1 Compatible Apple Clang 4.0 (tags/Apple/clang-418.0.60)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
>>> import scipy
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named scipy
>>>
What do I need to do to get python to run as my homebrew-installed python? Should this fix my problem and allow me to import scipy?
Homebrew puts things in a /usr/local/Cellar/<appname> directory, if I'm not mistaken. You should find the bin of the python in there and put it in your path before hitting /usr/bin.
For example, on my 10.8, python is located at /usr/local/Cellar/python/2.7.5/bin and I put that directory before /usr/bin/python in my PATH variable.
I do that similarly for other instances of me wanting to use homebrew version of an app, another example being sqlite.