Python calling function inside other function not working - python

This is what I have right now:
def open_file():
file_name = input("What is the name of the file you want to open?")
while True:
try:
file = open(file_name, 'r')
header = file.readline()
return (file)
break
except FileNotFoundError:
file_name = input("What is the name of the file you want to open?")
def process_file():
file = open_file()
print(file)
def main():
process_file()
I can't even get it to get to prompting me for the file name I want to open. Doesn't that mean it's not a problem with my loop but the way I am calling my functions?

Assuming you called your module something like foo.py
You could add this bit of code:
if __name__ == '__main__':
main()
And then in the console run:
>>python foo.py
For an explanation of why this works, you can see this answer: What does if __name__ == "__main__": do?

You need to call main() to run your code. If you do that it works just fine.

You need to call main() in order for your code to run.

Related

Get instance from a running code in Python?

I built a code in python with multi classes and threads, after I start the code and because of While True loop, the Code keeps running and writing in each step a Report. I need to link an outside function to the running Code to print the report.
example :
Running code:
import threading as TH
def WriteTXT():
file = open('File.TXT','a')
file.write('Test_WriteTXT')
file.close()
runLoop()
def runLoop():
th.start()
th = TH.thread(target = WriteTXT)
th.start()
Outside function :
def report():
file = open('File.TXT','w')
Txt_file = file.read()
print(Txt_file)
How to call report function and link it to the Running code to print Txt_file?
All you would do is call runLoop(), WriteTXT(), and report() functions at the end of the code. You also have to import threading "as" TH instead of "ad", and add the missing colon (:) when defining the WriteTxt function. The new code might look like this below:
import threading as TH
def WriteTXT():
file = open('File.TXT','a')
file.write('Test_WriteTXT')
file.close()
runLoop()
def runLoop():
th.start()
def report():
file = open('File.TXT','w')
Txt_file = file.read()
print(Txt_file)
WriteTxt()
th = TH.thred(target = WriteTXT)
th.start()
runLoop()

Python program with main() method does not run

def main():
names = []
for line in ins:
number_strings = line.split() # Split the line on runs of whitespace
data.append(numbers_strings) # Add the "row" to your list.
print(data)
I tried using this code to print a text file that looks like this
name num1 num2 C/N
I am trying to print this but when I run the command "python3 file.py" no output occurs. instead of printing the contents of the file I am putting in
Unlike in C, execution in python does not begin from the main method, as python follows a top-down approach. What you'll need to do is explicitly invoke the main method to have it run.
def main():
...
main()
If you want the main method to run only when invoked through the script (and not when imported), specify under what __name__ it should run:
def main():
...
if __name__ == '__main__':
main()
For more information, read
What does if __name__ == "__main__": do?
Understanding the main method of python
If you just want to execute that code you can forget about the main function and just write your code
names = []
for line in ins:
number_strings = line.split() # Split the line on runs of whitespace
data.append(numbers_strings) # Add the "row" to your list.
print(data)
If you do want to use a main function follow the community wiki answer.

Call function from a file B in a loop in file A

I have a python file B with all my function and a main code which is in loop of 0.25 sec, and I want to call this file in a loop in my file A. Can you get my weird mind ?
What I did but only read the loop from file B once :
#FileA
while 1:
from FileB import *
And my file B :
#FileB
while t<0.25:
#my stuff
Thanks.
PS : I forget to mention that i can't modify the file B.
The import statement only reads the target module one time.
If you have control of both files, I'd suggest that you make your loop a function in file B:
def main():
while t<0.25:
#my stuff
if __name__ == '__main__':
main()
Then you can call it repeatedly from file A:
from fileB import main as Bmain
while 1:
Bmain()
If you don't have control of the source code for the files (meaning: if the code comes from someone else), there are a few options. Probably the easiest and fastest to code would be to use the os.system(command) function to run the contents of fileB in a separate process.
You should use functions, you don't have any functions in your questions. Here is an example:
# fileA.py
import time
from fileB import myFunction
def main():
while True:
ret = myFunciton()
time.sleep(3)
main()
# fileB.py
def myFunction():
print "running myFunction"
return "result"

Using sys.argv from another .py file - python

I have a file (test.py) that receives sys.argv from the console/bash:
import sys
def main():
ans = int(sys.argv[1])**int(sys.argv[1])
with open('test.out', 'w') as fout:
fout.write(str(ans))
if __name__ == '__main__':
main()
Usually, I could just do $ python test.py 2 to produce the test.out file. But I need to call the main() function from test.py from another script.
I could do as below in (call.py) but is there any other way to run pass an argument to sys.argv to main() in `test.py?
import os
number = 2
os.system('python test.py '+str(number))
Please note that I CANNOT modify test.py and I also have a main() in call.py which does other things.
You can use your program as it is. Because, irrespective of the file invoked by python, all the python files will get the command line arguments passed.
But you can make the main function accept sys.argv as the default parameter. So, main will always take the sys.argv by default. When you pass a different list, it will take the first element and process it.
test.py
import sys
def main(args = sys.argv):
ans = int(args[1])**int(args[1])
with open('test.out', 'w') as fout:
fout.write(str(ans))
call.py
import sys, test
test.main()
Write that like:
import sys
def main(num):
ans = int(num)**int(num)
with open('test.out', 'w') as fout:
fout.write(str(ans))
if __name__ == '__main__':
main(sys.argv[1])
so that your main() function doesn't have to know about sys.argv - it just handles the parameters being passed in to it.
Without modifying test.py you can still run it just as you have it, just do call.py:
import test
test.main()
then $ python call.py ARG will still work. Since you've already imported sys in test, you don't need to reimport it unless you want to use sys in call.py. Note that sys.argv[0]=='call.py' not test.py if use test through call.
Create a function to do your calculation and file writing, which can be called from any other module:
power.py:
import sys
def power(arg):
ans = arg ** arg
with open('test.out', 'w') as fout:
fout.write(str(ans))
if __name__ == '__main__':
power(int(sys.argv[1]))
other.py:
import power
power.power(2)

Why isn't atexit registering in python?

I have a loop in Tkinter:
def main():
#Global Variables
windows = []
buttons = []
labels = []
messageboxes = []
global theme
theme = 0
listboxes = []
global register
register = []
global path
path = ""
# Lotsa' Code
Tkinter.mainloop()
if __name__ == "__main__":
main()
def save_f():
global register
outFile = open('FobbySave.txt', 'wb')
pickle.dump(register, outFile)
outFile.close()
global register
#At Quit
atexit.register(save_f)
atexit fails. But when I try to print register it has no problem. save_f worked when I put it in the Tkinter loop, but atexit didn't. So can somebody tell me what am I doing wrong?
P.S.
Sorry forgot to write atexit the first time. But it's in my code.
Edit: Orginal code down here
import pickle
import atexit
def save_f():
global register
outFile = open('Something.txt', 'wb')
pickle.dump(register, outFile)
outFile.close()
atexit.register(save_f)
OK turns out the problem was that I needed atexit.register(save_f) instead of atexit.register(save_f()).
You're not supposed to make a function call!
Looking at your code I would suggest to try this instead:
def main():
# ... everything in main ...
Tkinter.mainloop()
def save_f():
outFile = open('FobbySave.txt', 'wb')
pickle.dump(register, outFile)
outFile.close()
#At Quit
atexit.register(save_f)
if __name__ == "__main__":
main()
The problem might have been that you initialize your atexit after you run the main method. So after the code gets killed (and stops executing) you try to add the atexit method.
Your basic script works for me, provided I import atexit and set register to something. e.g.:
import pickle
import atexit
def save_f():
outFile = open('Something.txt', 'wb')
pickle.dump(register, outFile)
outFile.close()
register = 1
atexit.register(save_f)
(note that global isn't necessary either). In cases such as this, you should make sure that you don't have another file named atexit.py in the current directory or somewhere else on your PYTHONPATH ...

Categories