I'm trying to debug a script inserting print() commands to see the states of variables. But those commands don't seem to work. When I debug line by line using PyScripter it just skips those lines. I'm using Python 3. The problem is in a method of a class defined in a .py file, called from another .py file. I insert part of the code below.
class BaseGen:
def duracion(self, rangos, anio, semanas, verificar_ver_py=True):
print('some string')
The calling line is:
duracion = base.duracion(rangos_parte, anio, semanas)
The problem was with PyScripter. I tried the same code on the Python console and it was just fine.
Related
def greet(name):
"""
This function greets to
the person passed in as
a parameter
"""
print("Hello, " + name + ". Good morning!")
This is a basic example for defining a function, and when I run this code on Python 3.8.5 by VSC, the result is like below.
>>> def greet(name):
...
File "<stdin>", line 2
^
IndentationError: expected an indented block
It says that there is an indentation error but I really don't know why. And also, line 2 is not just blank but according to the result, line 2 seems like blank.
for number in range(5):
print("Thank you")
>>> for number in range(5):
...
File "<stdin>", line 2
^
IndentationError: expected an indented block
Same error for 'for'. Can anyone help?
Right now, you are running the Python script line-by-line by placing the VS Code cursor on each line of code and then pressing shift+enter. This utilizes the Python Interactive window afaik. It works fine for running individual lines but if you want to run a collection of lines that include indentation e.g. a for loop or function definition, then select all of those lines together and then press shift+enter. You would need to do this for code that's indented, for example:
def greet(name):
print("Hello, " + name + ". Good morning!")
Alternatively, if you have read Getting Started with Python in VS Code and specifically installed the Python extension for VS Code then you will be able to click the Run Python File in Terminal button (it looks like a Play icon) to run your Python script.
Alternatively, you can launch a Terminal Window in VS Code and manually run the Python script using python3 hello.py (or potentially python hello.py, depending on your Python installation).
You should not press Shift+Enter to run the code in the terminal line by line.
Because the REPL will add an Enter to start a new line automatically like this:
You can select all of the codes then send them to the REPL:
I am currently trying to run a .py file but in a loop.
Just for a test I am using
I = 0
while I<10:
os.pause(10)
open(home/Tyler/desktop/test.py)
I = I + 1
I am sure this is a very simple question but I can't figure this one out.
I would also like to add in the very end of this I have to make this run infinitely and let it run for some other things.
There are a few reasons why your code isn't working:
Incorrect indentation (this may just be how you copied it on to StackOverflow though).
Using os without importing it.
Not using quotes for a string.
Mis-using the open function; open opens a file for reading and/or writing. To execute a file you probably want to use the os.system.
Here's a version that should work:
import os
i = 0
while i < 10:
os.pause(10)
os.system("home/Tyler/desktop/test.py")
i += 1
Python is indentation-sensitive, and your code is missing indentation
after the while statement!
Running the open command will not run the Python script. You can
read what it does here in the docs:
https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files
This stack overflow question talks about how to run Python that's
stored in another file
How can I make one python file run another?
I recommend wrapping the code you want to run in a function, e.g.
def foo():
print 'hello'
and then saving this in foo.py. From your main script, you can then do:
import foo
i = 0
while i < 10:
foo.foo()
i += 1
If you want to run something in an infinite loop, you need the condition for the while loop to always be true:
while True:
# do thing forever
A note on importing: The example I have given will work if the foo.py file is in the same directory as the main Python file. If it is not, then you should have a read here about how to create Python modules http://www.tutorialspoint.com/python/python_modules.htm
I've written a function which reads and runs a python script, then sends it's output to a text file.
I'm trying to get it to write a simple string, or the error in question, to the text file if the script it ran is broken/doesn't work.
Below is the code in question:
file_dir = a_dir[0]
file_name = a_dir[1][:-3]
with open(f'{self.output_directory}\\output_{file_name}.txt', 'w') as f:
try:
subprocess.call(
[sys.executable, file_dir], stdout=f)
except:
f.write("An error occured with the script")
The first part of it works fine - it does run a functioning file and writes the output.
Do I need to be more specific with the error exception? Any help would be greatly appreciated!
If your code works fine and sys.executable is being run then there will be no exception and so your f.write code won't be run. If there is an error in a program you run using subprocess this doesn't propagate to an exception in a program you run it from. You'd have to know something about this program to know that there was an error you could look at the [returncode][1] from the subprocess.call function call. Another option is that instead of running a new python interpreter you could load the module yourself and then run code from within it using try except blocks. If you can't rely on any structure to the file then you could read the file as text and then run the code within it using eval or exec within a try except structure, that being said if you don't know anything about the file in advance it is likely a massive security flaw for you to be executing it at all let alone within the context of your running application.
**late edit read the file as text vice test which was a typo
[1]: https://docs.python.org/3/library/subprocess.html#subprocess.Popen.returncode
I'm taking a Udemy course on Python (my first language) and the environment of choice is Jupyter. When I try to write that code in Sublime, I can't get the same output (there are no errors).
def splicer(mystring):
if len(mystring)%2 == 0:
return "Even"
else:
return "Odd"
names = ["Andy", "Eve", "Sally"]
list(map(splicer,names))
You need to print the result!
print(list(map(splicer,names)))
In Jupyter, it automatically prints the representation of a statement, where as when you're writing applications, you need to print if you want the result to be shown on the screen.
jupyter acts as a python interpreter, so if you enter an object it automatically prints the result underneath. Sublime is a text editor, so it is only executing the code you are giving it. It is running list(map(splicer,names)) but it is not displaying the object because you are not telling it to.
So the interpreter (jupyter) is executing your python code in real time and interpreting (printing to screen). The text editor is only executing your python code. Therefore, you need to add a print statement to your object to have the editor print the object to screen:
print(list(map(splicer,names)))
Today I managed to run my first Python script ever. I'm a newb, on Windows 7 machine.
When I run python.exe and enter following (Python is installed in C:/Python27)
import os
os.chdir('C:\\Pye\\')
from decoder import *
decode("12345")
I get the desired result in the python command prompt window so the code works fine. Then I tried to output those results to a text file, just so I don't have to copy-paste it all manually in the prompt window. After a bit of Googling (again, I'm kinda guessing what I'm doing here) I came up with this;
I wrote "a.py" script in the C:/Pye directory, and it looked like this;
from decoder import *
decode("12345")
And then I wrote a 01.py file that looked like this;
import subprocess
with open("result.txt", "w+") as output:
subprocess.call(["python", "c:/Pye/a.py"], stdout=output);
I see the result.txt gets created in the directory, but 0 bytes. Same happens if I already make an empty result.txt and execute the 01.py (I use Python Launcher).
Any ideas where am I screwing things up?
You didn't print anything in a.py. Change it to this:
from decoder import *
print(decode("12345"))
In the Python shell, it prints it automatically; but the Python shell is just a helper. In a file, you have to tell it explicitly.
When you run python and enter commands, it prints to standard out (the console by default) because you're using the shell. What is printed in the python shell is just a representation of what object is returned by that line of code. It's not actually equivalent to explicitly calling print.
When you run python with a file argument, it executes that script, line by line, without printing any variables to stdout unless you explicitly call "print()" or write directly to stdout.
Consider changing your script to use the print statement.:
print(decode("12345"))