How to resolve file "<input>", line 1 syntaxerror: invalid syntax? - python

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']
>>>

Related

Python Starter script

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...

Get the full path to the directory a Python file is contained in

Actually I found the solution of my main problem "Get the full path to the directory a Python file is contained in" from the previous answer : Find current directory and file's directory.
And the code below from the answer works well if I run my entire script, in other words, hotkey F5.
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
However, if I just select the two lines of the above code and run it, in other words, hotkey F9. Then I will receive the error below:
NameError: name '__file__' is not defined
So if anyone happens to know why the error occurs, please give a brief explanation.
Thanks a lot!
By the way, i used Spyder (Python 2.7).
Inside Spyder or any interactive python process, the constant __file__ is not defined.
When you run the whole script, Spyder basically run the following command:
$ python script.py
While, if you select those two lines, it's more like entering a interactive python process first, then interpret the statements:
$ python
Python 2.7.13 (default, Jun 12 2017, 17:25:44)
[GCC 5.3.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> dir_path = os.path.dirname(os.path.realpath(__file__))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name '__file__' is not defined
>>>
That's the difference.

Can't import PyQ in Python 3.6 : flat namespace error

This is the error message I am getting:
Python 3.6.0 (v3.6.0:41df79263a11, Dec 22 2016, 17:23:13)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from pyq import q
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-
packages/pyq/__init__.py", line 21, in <module> from . import _k
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-
packages/pyq/_k.cpython-36m-darwin.so, 2): Symbol not found: _b9
Referenced from:
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-
packages/pyq/_k.cpython-36m-darwin.so
Expected in: flat namespace
in /Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-
packages/pyq/_k.cpython-36m-darwin.so
My python version is 3.6 and pyq version is 4.0.1.
I installed pyq via pip and Python via regular OS install.
PyQ is a python interpreter embedded in kdb+ and the pyq module cannot be imported in a stand-alone python. There are three ways to use pyq:
At the q command prompt or in a q script start the line with a p) prefix and follow with a python statement. For example,
p)from pyq import q
p)print(q.til(5))
will print 0 1 2 3 4.
You can place your python code in a file with the .p extension and use it as you would a q script: execute from command line
$ q foo.p
or load using the \l command.
Finally, the pyq executable gives a convenient way to run a standard Python REPL either interactively or to execute python programs. Internally, pyq executes q python.q, so your code still runs inside a kdb+ instance. Note that when you run pyq, Python REPL takes over and you cannot interact with your kdb+ instance using the standard kdb+ IPC mechanisms. If you require such communications, use one of the two options described above.
I think I got a solution: will be able to run [import pyq] when you run your python script with pyq binary. Exactly as you run a regular python script python xxx.py, you need instead to run it as pyq xxx.py

Ubuntu 12.04 How To Run Python 3.3.2 Program In Terminal

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)

Executing modules as scripts

I am learn python now, and today, i met a problem
in
http://docs.python.org/release/2.5.4/tut/node8.html
6.1.1 Executing modules as scripts
When you run a Python module with
python fibo.py <arguments>
the code in the module will be executed, just as if you imported it, but with the
__name__ set to "__main__". That means that by adding this code at the end of
your module:
if __name__ == "__main__":
import sys`
fib(int(sys.argv[1]))
you can make the file usable as a script as well as
an importable module, because the code
that parses the command line only runs
if the module is executed as the
"main" file:
$ python fibo.py 50 1 1 2 3 5 8 13 21
34
but when i do this in shell, i got
File "<input>", line 1
python fibo.py 222
SyntaxError: invalid syntax
how to execute script correctly?
fibo.py is
def fib(n):
a,b=0,1
while b<n:
print b,
a,b = b,a+b
def fib2(n):
result=[]
a,b=0,1
while b<n:
result.append(b)
a,b=b,a+b
return result
if __name__ =="__main__":
import sys
fib(int(sys.argv[1]))
What exactly did you do in the shell? What is the code you are running?
It sounds like you made a mistake in your script - perhaps missing the colon or getting the indentation wrong. Without seeing the file you are running it is impossible to say more.
edit:
I have figured out what is going wrong. You are trying to run python fibo.py 222 in the python shell. I get the same error when I do that:
[138] % python
Python 2.6.1 (r261:67515, Apr 9 2009, 17:53:24)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> python fibo.py 222
File "<stdin>", line 1
python fibo.py 222
^
SyntaxError: invalid syntax
>>>
You need to run it from the operating system's command line prompt NOT from within Python's interactive shell.
Make sure to change to Python home directory first. For example, from the Operating system's command line, type: cd C:\Python33\ -- depending on your python version. Mine is 3.3. And then type: python fibo.py 200 (for example)

Categories

Resources