I have two .py files. The main_module is 'TS_File_analysis.py' and sub_module is 'Port_operations.py'.
Import sub_module in main_module.
from Port_operations import *
def main_menu():
try:
if r == 1:
print()
elif r == 2:
search_cmd_output()
elif r == 3:
port_analyze_drops()
elif r == 4:
print('Exit out.! Good bye..:)')
return
else:
print('Entered option was not valid.\n')
main_menu()
except ValueError as ex:
print('Din\'t choose any option.\n')
main_menu()
Import main_module in sub_module file.
from TS_File_analysis import main_menu
def port_analyze_drops():
try:
if int(r2) == 1:
get_output_of_port_drops()
elif int(r2) == 2:
get_output_of_port_errors()
elif int(r2) == 3:
del_res_file(temp_result2)
main_menu()
else:
print('Entered option was not valid.\n')
port_analyze_drops()
except ValueError as ex:
print('Din\'t choose any option.\n')
port_analyze_drops()
return
With the initial run, we can go from main_module to sub_module successfully and come back to main_module. Again if I want to go from main_module to sub_module it fails with the below traces.
Traceback (most recent call last):
File "C:\Users\user1\Documents\Python\Source\Workspace\TS_File_Analysis\TS_File_analysis.py", line 151, in <module>
main_menu()
File "C:\Users\user1\Documents\Python\Source\Workspace\TS_File_Analysis\TS_File_analysis.py", line 95, in main_menu
port_analyze_drops()
File "C:\Users\user1\Documents\Python\Source\Workspace\TS_File_Analysis\Port_operations.py", line 20, in port_analyze_drops
main_menu()
File "C:\Users\user1\Documents\Python\Source\Workspace\TS_File_Analysis\TS_File_analysis.py", line 94, in main_menu
port_analyze_drops.__module__
NameError: name 'port_analyze_drops' is not defined
Expectation is to switch from main_module to sub_module and vice versa as many times as you try to switch.
From the code snippets provided it is hard to see the module hierarchy, import structure, calling tree, and namespace. I would have to see the main_menu module to understand the import structure. If you can post that it would be helpful.
I can see two potential problems that may be confusing you.
First of all Python "import STAR" statements with 'import *' are totally frowned upon. It is considered poor namespace management practice, because you can easily clobber other object names without realizing it. It looks like you may be clobbering the main_menu function with your IMPORT STAR. Please provide the full source code for the 'TS_File_analysis.py' file.
Second, it is better to structure your modules with a top-level main module e.g., "app_main.py" that imports the other supporting modules. Your main_menu() function should be at the bottom of the app_main.py file and be run after the other modules are imported into it, not the other way around. Submodules should not be importing the main module.
Related
Just trying to handle some IndexError while using sys. Searched a lot on how to do it, and I've come to a final "solution", but I don't know why it's not working.
Actual code
#!/usr/bin/python3
import sys
t = sys.argv[1]
u = sys.argv[2]
try:
t = sys.argv[1]
except IndexError:
print("no arg 1")
try:
u = sys.argv[2]
except IndexError:
print("no arg 2")
Output
Traceback (most recent call last):
File "/home/try.py", line 9, in <module>
t = sys.argv[1]
IndexError: list index out of range
I don't know why it errors out, since I have set previously the sys.argv[1] inside the try block
Could anyone help me out on this?
EDIT:
I was able to find a way around for this, which is, a separate script for different stuff.
The issue comes from the t and u definitions above the two try blocks. Get rid of those and keep your try blocks and you should be good.
In addition to the spurious statements at the start (i.e. outside of the try statement), I think you are misunderstanding how array subscripting works in Python.
Python arrays start from subscript 0 (not 1). For an array with 2 elements, their subscripts are 0 and 1. So your code should be:
import sys
try:
t = sys.argv[0] # <<<
except IndexError:
print("no arg 1")
try:
u = sys.argv[1] # <<<
except IndexError:
print("no arg 2")
Searched a lot on how to do it ...
Can I point out that this is NOT a good way to learn to program ... or to find the bugs in your code. You should not be searching for "solutions". You should be reading your code, and looking at the evidence and trying to figure out what you have done wrong.
For example, the version of the code in your question actually produces this output:
$ ./test.py
Traceback (most recent call last):
File "./test.py", line 5, in <module>
t = sys.argv[1]
IndexError: list index out of range
It says that the error is on line 5. Then you look at the code and see that line 5 is NOT in the try: statement.
Secondly, you should be consulting reliable resources on Python; e.g. the official documentation, a textbook, or a decent tutorial. They will explain clearly how array subscripting works, for example.
elif(ch==2):
fh=open("emp1.txt","rb+")
fo=open("temp.txt","wb+")
ecode=input("Enter the Ecode :")
rec=(" ")
try:
while True:
emp1= pickle.load(fh)
if (emp1.ecode!=ecode):
pickle.dump(emp1,fh)
except(EOFError):
fh.close()
fo.close()
os.remove("empl.txt")
os.rename("temp.txt","emp1.txt")
print("")
running the following code gives me this error:
Traceback (most recent call last): File
"C:\Users\hello\Desktop\bhavi\python programming\Employ.py", line 78,
in
emp1= pickle.load(fh) EOFError
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"C:\Users\hello\Desktop\bhavi\python programming\Employ.py", line 85,
in
os.remove("empl.txt") FileNotFoundError: [WinError 2] The system cannot find the file specified: 'empl.txt'
What should i do now??
You should fix your path. In the first case, you write "emp1.txt"; and in the second, you write "empl.txt". If you look carefully, you should notice that there is a difference in those two strings.
Hint: '1' != 'l'
Your code could probably be refactored as well. While it is not possible for others to test your code since it is very incomplete, the following should work in its place. You will still need to verify it works.
elif ch == 2:
with open('emp1.txt', 'rb+') as fh, open('temp.txt', 'wb+') as fo:
ecode = input('Enter the Ecode: ')
while True:
try:
item = pickle.load(fh)
except EOFError:
break
else:
if item.ecode != ecode:
pickle.dump(item, fo)
os.remove(fh.name)
os.rename(fo.name, fh.name)
print()
I would use shelve, its much easier to use and it doesn't come up with to many errors in my experience. shelve is built on pickle but it just simplify it.
here is a short tutorial
http://python.wikia.com/wiki/Shelve
Is there something that I could use to catch errors in python without using a try/except?
I'm thinking of something like this:
main.py
from catch_errors import catch_NameError
print(this_variable_is_not_defined)
catch_errors.py
def catch_NameError(error):
if type(error) == NameError:
print("You didn't define the error")
The output would be:
You didn't define the error
Instead of:
Traceback (most recent call last):
File "main.py", line 1, in <module>
print(this_variable_is_not_defined)
NameError: name 'this_variable_is_not_defined' is not defined
It can be done by creating a context manager, but it gives questionable benefit over an explicit try:except:. You will have to use the with statement, so it will be clear where behavior will change. In this example, I am using contextlib.contextmanager to do this, which saves the tedium of creating a class with __enter__ and __exit__ methods.
from contextlib import contextmanager
#contextmanager
def IgnoreNameErrorExceptions():
"""Context manager to ignore NameErrors."""
try:
yield
except NameError as e:
print(e) # You can print whatever you want here.
with IgnoreNameErrorExceptions():
print(this_variable_is_not_defined)
This will output
name 'this_variable_is_not_defined' is not defined
I am trying to call a tcl proc in a python program.
The tcl script starts with
proc scale_wigner-seitz_radii { } {
(I am not sure if I can put the full proc here, as this is a part of a licensed program).
This program is called by my python script:
#!/usr/bin/python3
import sys
from numpy import arange
from tempfile import mkstemp
from shutil import move, copy
from os import remove, close, mkdir, path
import Tkinter
def repll(file_path, pattern, subst):
print(pattern)
print(subst)
print(file_path)
r = Tkinter.Tk
# fullpath = str(subst) + "/" + file_path
fh, abs_path = mkstemp()
with open(abs_path, "w") as new_file:
with open(file_path, "r") as old_file:
for line in old_file:
new_file.write(line.replace(pattern.strip(),
str(subst).strip()))
r.tk.eval('source /home/rudra/WORK/xband/create_system_util.tcl')
r.tk.eval('proc scale_wigner-seitz_radii')
copy(abs_path, path.join(str(subst), file_path))
inpf = str(sys.argv[1])
a = []
print (inpf)
with open(inpf, "r") as ifile:
for line in ifile:
if line.startswith("lattice parameter A"):
a = next(ifile, "")
print(a)
for i in arange(float(a)-.10, float(a)+.10, 0.02):
if not path.exists(str(i)):
mkdir(str(i))
repll(inpf, a, i)
I havn't make a minimal example, because this seems better than explaining in english.
At the very end of def repll, it is calling the tcl proc. I have never encountered a tcl script before, and found the calling process from this question.
But when I am running this, I am getting error:
Traceback (most recent call last):
File "xband.py", line 41, in <module>
repll(inpf, a, i)
File "xband.py", line 24, in repll
r.tk.eval('source /home/rudra/WORK/xband/create_system_util.tcl')
AttributeError: class Tk has no attribute 'tk'
How I can solve this?
After Donal's Comment Thanks for your reply. After following your suggestion, I got same error from source line.
Traceback (most recent call last):
File "xband.py", line 41, in <module>
repll(inpf, a, i)
File "xband.py", line 24, in repll
r.tk.eval('/home/rudra/WORK/xband/create_system_util.tcl')
AttributeError: class Tk has no attribute 'tk'
Sorry if its silly, but since the tcl is in different file, I must source that first, right? And, as I said, this is the first tcl code I am looking at, please be elaborate.
The problem seems to be this line:
r = Tkinter.Tk
My guess is, you think this is creating an instance of Tk, but you're merely saving a reference to the class rather than creating an instance of the class. When you instantiate it, the object that gets returned has an attribute named tk, which the object internally uses to reference the tcl interpreter. Since you aren't instantiating it, r (which points to Tk) has no such attribute.
To fix it, instantiate the class by adding parenthesis:
r = Tkinter.Tk()
r will now be a proper reference to a Tk object, and should have a tk attribute, and with that you can call eval on raw tcl code.
i have written a simple code that should draw a square, see below:
from turtle import Screen,Turtle
def draw(directions,length,angle,x=0,y=0):
s = Screen
t = Turtle
t.up()
t.setpos(x,y)
t.down()
# iterate over directions
for move in directions:
if move =='F':
t.forward(length)
elif move == 'L':
t.lt(angle)
elif move =='R':
t.rt(angle)
else:
pass
s.exitonclick()
but I get an error message that I dont understand. See below
>>> draw('FLFLFLFL',50,90)
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
draw('FLFLFLFL',50,90)
File "C:/Documents and Settings/RonnieE/Mina dokument/GradSchool/CSC401/Homework
7/test1.py", line 11, in draw
t.up()
TypeError: penup() missing 1 required positional argument: 'self'
What did I do wrong?
This:
s = Screen
t = Turtle
should be:
s = Screen()
t = Turtle()
Otherwise, s and t are just new names for the Screen and Turtle classes. Call the class to generate an instance.
Also, s.exitonclick() should be inside the draw definition (aligned with the for).