I made my first python program of hello world.
Every time i save it,it cannot be open in the program.
And the program just blink and flashes away.
I read few line 'invalid syntax'.
here what I WROTE:
>>>print('hello world')
then i saved it as p.py and try to run it on program and zilch.
I have a feeling you are reading the book 'The self taught programmer'? What you need to do is realize the shell and the notepad are two different things.
Do this.
Open up the IDLE shell, but then go to the file-new-new file
This should open a new window. Now this window, simply put the Print("Hello, taxation is theft"). Now, save this window, as whatever you want. Now, in the same window, with both the shell open, and this new window, click F5 or run 'run module'.
You'll see what you made in the notepad will run on the shell window. It will only run once. The next step is to practice running it 5 times, then 100 times. You'll get there bud.
While saving .py file you must have beeen saving it as it is, containing other whitespaces and charater like ">>". remove ">>> " fr
In python 2.7 print looks like this:
print "hello world"
In python 3 it looks like this:
print( "hello world" )
Run your code with python3:
python3 p.py
Related
I can't find out how to open a python file from one python file in another window. The code I have opens it in the same window and both scripts are running in one window so.. BUGS!
I have tried everything like changing "popen" to "run" changing "shell=True" to "shell=False" But they all just crash the program. Here is the code I have:
elif(cmd=="Run dev console"):
okaylol = ("Okay!")
print(okaylol)
devconopen = ("devcon.bos.py")
subprocess.Popen(devconopen, shell=True)
Also it's a program like a weird MS-DOS where you type commands and they do stuff. So this code is like: If you type "Run dev console" it will print "Okay!" then TRY to open the other python file "The dev console"
I wrote some very simple code:
def yo():
text = "hi there"
print(text)
print(text)
yo()
I ran this in Spyder and online compilers without error. Obviously it spits out:
hi there
hi there
But when I run this in VS Code terminal using the "Run Python file in terminal" play button I get
"SyntaxError: invalid syntax"
for line 1 (the def line).
When I type yo() into the terminal itself, I get the expected output of:
hi there
hi there
Why is do I get a different result from these? I executed other simple bits of Python in VS Code using the "play" button without issue. It goes without saying that I have the python extension and interpreter installed.
UPDATE: I restarted VS Code and now the file runs without issue. I guess "did you restart the computer" really does solve the issue sometimes...
Your function - yo(), is being defined, however Visual Studio Code does not know how to run it. To fix this, try adding the if __name__ == '__main__': clause. Here is your full code:
def yo():
text = "hi there"
print(text)
print(text)
if __name__ == '__main__':
yo()
Here is some more information about if __name__ == '__main__':
If that doesn't fix it, you must have some formatting issues or some different settings of Visual Studio Code. You could do the following things.
Make sure you're running the right file
Delete all of the code and paste it in again
Reset your Visual Studio Code settings
Make sure your settings for Tab are 4 spaces.
Disable terminal.integrated.inheritEnv in Settings
If all else fails, try these:
You should use the exit() command in the terminal to end python session. Then re-run and see if anything works.
Run your code using 'Start without debugging'.
I recently started using idle3 to follow along with some course material as recommended by the instructor. Opening a new shell and running python code works just fine, the problem is when i save the file and later try to reopen it to continue on with the course work.
When ever i open the designated .py file, it only loads up in regular text, i can no longer execute new code, the line break doesn't have the ">>>" before each line, it won't even give any output
How can i open a saved file and continue on implementing code?
The basic use of the IDLE is for 2 thing, text editor and interactive console.
The interactive console allow you to write any python code and see it running immediately, great quick calculation and/or testing code until you get the desired result.
The save option (File -> Save) is deceptive however, because it save everything as you see including the >>> so saving as .py just doesn't work, or not without some extra work, namely removing all the >>> and all other undesired stuff, so is more like screenshot of sort.
The text editor mode is, well, just that but specialized for python with its syntax highlight and whatnot, use it to write your modules or whatever else, save it as .py and run the code by pressing F5 in order to test it, which will open a new interactive console with all that code loaded into it or would load it into a previously open one in which case it will reset it first, and that means that anything not in the file will be discarded (but you can scroll up can copy-pasted again if needed)
So for example, in a file you have
def greetings(name):
print("hello",name)
and you open it with the text editor mode of IDLE, simply run (F5) and you now have access to that function in the interactive console
>>> greetings("bob")
hello bob
>>> a=23
>>>
and lets make a new variable with some value
Now lets said we go back to the file and add some more stuff and now it looks like
def greetings(name):
print("hello",name)
def add(a,b):
return a+b
b=42
and run it again, this reset the console, which is indicated a msj like this containing the path of the loaded file
====== RESTART: C:\Users\Copperfield\Documents\StackOverflow\example.py =====
>>>
now we have the greetings and add function but the variable a from before is now loss
>>> a
Traceback (most recent call last):
File "<pyshell#6>", line 1, in <module>
a
NameError: name 'a' is not defined
>>>
but you have b
>>> b
42
>>>
So, use the text editor mode to write all the stuff you want to keep and in the interactive console play with it to test that is indeed the thing you want, and if not just go and edit it some more...
In a linux terminal typing
python script.py
Will run run script.py and exit the python console, but what if I just want to run a part of the script and leave the console open? For example, run script.py until line 15 and leave the console open for further scripting. How would I do this?
Let's say it's possible, then with the console still open and script.py run until line 15, can I then from inside the console call line fragments from other py files?
...something like
python script.py 15 #(opens script and runs lines 1-15 and leaves console open)
Then having the console open, I would like to run lines 25-42 from anotherscript.py
>15 lines of python code run from script.py
> run('anotherscript.py', lines = 25-42)
> print "I'm so happy the console is still open so I can script some more")
I'm so happy the console is still open so I can script some more
>
Your best bet might be pdb, the Python debugger. You can start you script under pdb, set a breakpoint on line 15, and then run your script.
python -m pdb script.py
b 15 # <-- Set breakpoint on line 15
c # "continue" -> run your program
# will break on line 15
You can then inspect your variables and call functions. Since Python 3.2, you can also use the interact command inside pdb to get a regular Python shell at the current execution point!
If that fits your bill and you also like IPython, you can check out IPdb, which is a bit nicer than normal pdb, and drops you into an IPython shell with interact.
if you want to run script.py from line a to line b, simply use this bash snippet:
cat script.py|head -{a+b}|tail -{b-a}|python -i
replace {a+b} and {b-a} with their values
You could use the python -i option to leave the console open at the end of the script.
It lets your script run until it exits, and you can then examine variables, call any function and any Python code, including importing and using other modules.
Of course your script needs to exit first, either at the end or, if your goal is to debug that part of the script, you could add a sys.exit() or os._exit() call where you want it to stop (such as your line 15).
For instance:
import os
print "Script starting"
a=1
def f(x):
return x
print "Exiting on line 8"
os._exit(0) # to avoid the standard SystemExit exception
print "Code continuing"
Usage example:
python -i test_exit.py
Scrit starting
Exiting on line 8
>>> print a
1
>>> f(4)
4
>>>
You cannot do that directly but you can do something similar from inside Python console (or IDLE) with exec :
just open you favorite Python console
load wanted lines into a string and exec them :
script = 'script.py'
txt = ''
with open(script) as sc:
for i, line in enumerate(sc):
if i >= begline and i<= endline:
txt = txt + line
exec(txt)
You can even write your own partial script runner based on that code ...
EDIT
I must admit that above answer alone really deserved to be downvoted. It is technically correct and probably the one that most closely meet what you asked for. But I should have warned you that it is bad pratice. Relying on line numbers to load pieces of source files is error prone and you should avoid it unless you really know what you are doing and why you do it that way. Python debugger at least allows you to control what are the lines you are about to execute.
If you really have to use this solution be sure to always print and double check the lines that you are about to execute. IMHO it is always both simpler and safer to copy and past lines in an IDE like IDLE that is packaged into any standard Python installation.
I am interested in a small python application, which can be downloaded here:
https://launchpad.net/treemap
If you run it, like this:
python treemap-basic.py examle-world-population.txt
It works just fine.
The problem is that even if I type a print command in the "treemap-basic.py" file:
print "Hello World !" # treemap-basic.py
I cannot see the message "Hello World !" at the Terminal. Why?
I downloaded this script, and inserted
print "Hello World"
on line 64. When simply trying ./treemap-basic.py on the terminal, you get an IndexError since treemap-basic.py expects a command line argument. When you specify a file to work on:
./treemap-basic examle-world-population.txt
You see a bunch of output in stout. If you scroll up to the top (right below where you first entered the command in the terminal) you should see "Hello World" as the first line of output.