SyntaxError when running with Python 2 - python

I have a Python script called "controlled_biomass_exp.py" that generates some data and plots it. Its over 100 lines long so I don't want to dump it all here.
I can run it from Ipython in the terminal once and it works fine. If I repeat the command to run the script again with:
In [3]: run controlled_biomass_exp.py
I get:
File "< ipython-input-3-3ec3d096e779>", line 1
run controlled_biomass_exp.py
^
SyntaxError: invalid syntax
(The carrot is pointing at the last letter of the filename, "p".)
I get the same problem if I run any other python script after running this one. If I quit Ipython in the terminal and restart it the problem "re-sets". I can run other scripts fine, until I run the broken one once. I haven't encountered a problem like this before. Any help directing me where to look for solutions much appreciated.

It appears that your script controlled_biomass_exp.py overwrites run in your current namespace.
This toy example will produce a similar problem:
# file: test.py
run = "hello world!"
print(run)
Calling run in IPython is just a shortcut for %run which is a built-in magic function. Once you overwrite run (e.g. as shown in my toy example) you cannot use the shortcut anymore.
However, %run controlled_biomass_exp.py should still work for you.

Related

save Python variables after running it from terminal

I am using python and Visual Studio code to develop my code. I can run my scripts successfully (Using Run Python File in Terminal). However, this is very inconvenient since after each run I go back to the terminal window and do not have access to python, therefore, I will lose the variables in the previous run so I have three options: 1- Print all the variables I want to screen (This is clearly not scalable). 2- Run the file again. 3- Run the Python file in an interactive window(Ipython).
Option 3 is exactly like running the file in a Jupyter Notebook which is very convenient since you can create a cell below the current cell and keep using the variables after one run.
I would like to know what is the best method to run the python script from the terminal (Pycharm, VS code,...) and can work with variables after (not like every time you forgot to print something you run the file again?
If you set a breakpoint then debug your code (f5), on the bottom of VSCode there is a Debug Console, you can type in debug command there (print(), type(), etc). That seems like it might be what you are looking for.
Try shift + enter on each line this will open the terminal with python
Or try to run .ipynb files instead of .py files in vscode

Can't run Python file via Command Prompt, File is not defined error

I am new to Python and currently doing a basic python course to learn. I have been running code all day via the Command Prompt and it has been working fine. For some reason though it has stopped working and python files I try to run are returning the following error:
Traceback (most recent call last):
File "", line 1, in
NameError: name 'hello' is not defined
As per the screen shot and the numbers on it, I performed the following steps in an attempt to run the file:
change to the folder where file is saved
run 'dir' to list all files. I am trying to run 'hello.py'. This contains the code: print('hello simon!')
I can run the file by just typing hello.py into the command prompt, this works ok
I can also run with: python hello.py - this works ok
when I activate Python by typing Python --> Enter, this starts the interpreter ok. However if I then try to run by typing hello.py I get the error message.
This has worked ok all day, I have not changed anything on my PC (to the best of my knowledge!) but just started to get this error a few hours ago. I have looked all over the internet for solution but found nothing. I have uninstalled and re-installed Python, restarted etc... all to no avail.
I am running Python 3.6.5 on a Windows 7 64 bit PC.
It won't let me attach a picture so here is link to screenshot of Command Prompt and error: https://i.stack.imgur.com/BBUe5.jpg
I hope someone can help me with this please
Thankyou
You are not supposed to execute hello.py in the Python Interpreter. It won't work. When you type in python and hit Enter in your Command Prompt, Just type this,
>>> print('hello simon!')
And hit Enter, it would definitely work. Because the interpreter is supposed to execute a code line by line. So if you want to run a Python Script then do not execute it in the Interpreter.
The problem is that when you write python (alone), the command line calls python shell and the following commands are run inside the python shell and not in the command line anymore. Calling a script from the shell has a different format (look it up). You can enter exit() to exit the shell back to command line again
What you are trying to achieve is you are running Hello.py inside Python.
Not with Python.
You need to run Hello.py with Python. As python is interpreter over here.
>>>python
means you are going inside python shell
>>>print('hello simon!')
Is equivalent to your program.
You are running your Python Script as you should and it's working. If you added Python to your path you can run Script you only need to call the Script "hello.py". If you have more than one intepreter, or you didn't added it to your path then you can call it like this "C:\path\to\python\interpretet\pythonxxx.exe" "c:\path\to\python\script.py" you can enven pass arguments to it "C:\path\to\python\interpretet\pythonxxx.exe" "c:\path\to\python\script.py" --argument
When you type python in a shell, then interactive mode is activated. This is like a shell where you type commands and got interpreted right away, in the same way as cmd and powershell works, but for python. This way you can test snippets, or just do simple stuff overly complicated like this
import os
ls = os.listdir(os.path.abspath('c:/'))
def print_dir():
for file in ls:
print(file)
Wich in cmd would be dir c:\ or in powershell ls c:\. The point is that you can test libraries, explore objects, replace the shell or just have fun.

Trouble using custom code from a separate file

I'm getting ready to start a job (in C#.NET) where having some Python experience is a plus. I did some reading about it a year or two ago, and picked up another book (Python 3 Object Oriented Programming by Dusty Phillips). I'm at the first code example, and having a really stupid issue.
I created my first class in a separate file, first_class.py. It's saved in my C:\Docs\Continuing Education\Object Oriented Python\Chapter 2 folder:
class MyFirstClass:
pass
He then says "run the command python -i first_class.py". I open up the ?Python 3.5 Console? (if that is what it's called), and put that in there. I wasn't quite expecting it to work because it's executing from a different folder than the file is in.
I tried executing the command again, with the fully-qualified location of the file with and without quotes, but neither of those worked. Seeing a few other answers around, I tried all three (without the folder, and with and without quotes) but omitting the .py extension, and that doesn't work. All of those commands so far have given the following error message with an error pointing to the end of the word "first_class":
SyntaxError: invalid syntax
I tried omitting the python part of the command since I'm already in the Python program, but that doesn't work either.
Next, I found this answer and changed the "current directory" to the folder I listed above. Same deal with and without the python and/or the .py.
I tried using the import function as well. That doesn't give any errors, so I thought it worked. I went on to the next command in the book:
>>>a = MyFirstClass()
Unfortunately, that gave the following error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'MyFirstClass' is not defined
I'm sure I'm just missing something ridiculously simple. If this is a duplicate, by all means, flag away.
When the text says run python -i /path/to/file it's expecting you to run that from a shell, not from within the python console.
The -i flag is a way to pass a file or list of files to python that will run and then dump you into the interactive prompt. Any code in the file will be in the global namespace, as if you had typed it into the interactive console.
Open up a cmd shell (or powershell) and run:
python -i "C:\Docs\Continuing Education\Object Oriented Python\Chapter 2\first_class.py"
Then you should be able to call your class
a = MyFirstClass()

Trouble running program with Python27-Newbie

okay, im a new guy at all this, just randomly picked it up with my neighbor and we are both stuck at this. We have been following this tutorial(here) and have made it to 6.6 in the tutorial. I have searched the forums looking for a way to get passed my problem but all the of questions people have are too complex for me as of right now. I am running windows 8.1 on my laptop, i have python27. So here we go i put in,
>>> cd c:\\py
and i get
File "<stdin>", line 1
cd c:\\py
^
SyntaxError: invalid syntax
Then i searched around and found a thread saying to use os.chdir so i gave that a shot and got;
>>> os.chdir("c:\\py")
>>> os.getcwd()
'C:\\py'
>>>
So my guess is that it worked? so then i go ahead and try to run my program like it says to do, so i put in
python hello.py
and i get this in return
>>> python hello.py
File "<stdin>", line 1
python hello.py
^
SyntaxError: invalid syntax
I'm literally stuck, i have no clue what to do now. If someone can help me through this i will love you long time.
Thank you
First of all, Python shell differs from system shell (cmd.exe). You try to run python script.py in Python interpreter instead of cmd.exe.
Open cmd.exe and type in python script.py to solve this. It'll run fine if it doesn't contain any errors. cd c:\\ doesn't work due to the same reason.
First quit() or exit() the Python interpreter (type one of them right in it) then type the commands you want to execute (such as cd) into terminal.
If you want to run code.py in Python interpreter, you can os.chdir("...") to the directory where your script resides and type import code. That may not work if your script contains
if __name__=="__main__":
All in all, Python interpreter is for running Python code right in it and command prompt (terminal, cmd.exe) is for running other non-GUI programs and much more.
You are in the python interpreter which is an interactive shell. You can consider it "scratch paper" to test out or try different things.
To run your script :
quit()
in the command prompt run python.exe hello.py ( on windows.. on *nix just python)

Issue with Python Batch file to run Python through Notepad++

EDIT: The code I wrote in my Python file was just this:
print "foo"
I'm using Windows XP Home Premium on this tiny little HP Mini 1000, and I want to run Python files, since we're learning it in school. I am aware of this topic, so I tried to run Python files using a batch file (python.bat), and I'm getting an error that says, "Can't find 'main' module in ''" whenever I run the batch file. I followed the instructions given here. All I did was change "Python26" to "Python33" because of the difference in versions.
Any idea what's wrong here? I really want to run Python files from Notepad++, so I don't want any alternative ways to run them.
This sounds like you don't have PYTHONPATH set up correctly. I suggest you review the documentation here:
http://docs.python.org/2/using/windows.html
Instead of calling Python, call cmd.exe and then use the set command to inspect which variables are set and how they are set. Run the exit command to leave the command shell. When you think you have the variables set up correctly, try again to run Python.
Good luck and have fun!
I use the command line interpreter or IDLE mostly (Win 8.1 now, but I've done so since Win XP SP2), but NPP is my main text editor, so I was curious about this issue.
When I was reproducing this, I was able to generate several errors, but the only one I got that was an exact match was when I failed to configure the Run option correctly.
You need to make sure to follow this step exactly in the instructions you were following. When you navigate to Run -> Run in Notepad++, you have to enter this exactly:
C:\Python33\python.bat "$(FULL_CURRENT_PATH)"
I am pretty sure you left out the "$(FULL_CURRENT_PATH)", or otherwise didn't add it correctly, as failing to do so causes exactly the same error on my end. Failing to include this means that when you run the batch script, you get the wrong input to the Python interpreter, causing the error.

Categories