Trouble using custom code from a separate file - python

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()

Related

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.

NameError issue with Desktop

I am new to python.
I am trying to run my first script... I think this is what is called.
I have following in a python doc called "intro.py":
print('hello world')
This is saved under my Desktop (running Windows).
When I go to cmd, I type:
>>> Desktop/intro.py
When I do this I get a response that says:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Desktop' is not defined
Can someone please explain to me my issue? Thanks
Windows shell refers to what you see, when you hit windows-button + r and then type cmd and hit enter.
To start your script: hit windows-button + r and then type cmd and hit enter
After that navigate in the command line to your desktop using cd and then type python init.py to execute your script.
It seems to me like you were already in the python shell, when you tried to start your script.
To see the difference open the command line like before: hit windows-button + r and then type cmd and hit enter, remember how your terminal looks like now, then type in python and note the three >>> at the beginning of the line. This is then called the Python shell.
You tried to execute windows commands in this python shell, which obviously does not work. However you could also theoretically write your script in this python shell. But this is really awkward.
I suggest you to use an IDE. If I'm not wrong IDLE comes with the python 3 interpreter already or I can recommend my personal favorite PyCharm.

Cant get basic Python script to work

this is my first time trying to get a Python script to work and not having much luck.
I have a file called 'alpha_script.py' with the following in:
#!/usr/bin/env python
print "the script is running now"
that is in the /bin folder of a project.
Then I run this in terminal
chmod +x alpha_script.py
nothing happens after I hit enter though, not sure if thats correct or not.
I can run the file just fine with a normal Python command but when I enter this in the terminal
./alpha_script.py
it returns this error message
./alpha_script.py: line 4: print: command not found
what am I doing wrong here?
The issue is in your shebang line -
#!/usr/bin/env python
^ Notice the extra space.
The extra space at the starting of the line is causing the issue (That shebang line is not getting picked up correctly) , remove that space and it should work.
There are roughly four things to check here.
Is the #!/usr/bin/env python literally at the very beginning of your file? Are there any "hidden" or whitespace characters preceding the the #!?
Do you actually have the /usr/bin/env utility present and executable? (You almost certainly do, it's standard in Linux and other forms of UNIX. But check anyway).
Do you have 'python' on your path, under exactly that name?
What version of Python do you have installed as python?
I suspect that you just have some space or something in front of your "shebang" (#!) marker. This will cause some shells to treat the entire file as a shell script and would give the error message that you're getting.
However, the broader lesson to learn is that every on of these things I've enumerated is imported to getting any sort of script running for any scripting language. You must have a valid "shebang" line (meaning that #! must be the very first characters of the script) ... the path after the #! must be valid ... if you're using env then the interpreter named after the space must be valid and on the path ... and lastly that Python changed from versions 2.x (and earlier) to the new 3.x (print is no longer a statement ... it's now a function and must be rendered as print() with the parentheses around its arguments).

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)

SyntaxError when running with Python 2

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.

Categories