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

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"

Related

How running process does reload new lib file code dynamically in python?

I want to use my project's new lib file. However, i don't hope to main progress stop running?
for example ,i have b.py:
import a
import time
def main():
for i in range(1000):
time.sleep(5)
print i
a.abc()
main()
a.py is
def abc():
print 'abc'
I want to modify my abc function in a.py to
def abc():
print '123'
When i finish modified abc function in a.py, I hope it worked at once in main process in a.py .
i remove a.pyc file, but it still print abc, not 123. How to print 123 when don't stop main progress?
Can't change main process. Because it is always running.
You might want to save your module hashsum and after every execution check if it changed and reload if so:
import hashlib
import time
import a
def main():
with open('a.py', 'rb') as f:
module_hashsum = hashlib.md5(f.read()).hexdigest()
for i in range(1000):
time.sleep(5)
print i
a.abc()
with open('a.py', 'rb') as f:
hashsum_temp = hashlib.md5(f.read()).hexdigest()
if module_hashsum != hashsum_temp:
module_hashsum = hashsum_temp
reload(a)
main()
Or just reload it after every execution.
Might aswell do some fancy checks for file's mtime, like it's done in django. But it will trigger reload even if you didn't change anything in a file and only did :wq in Vim (just saved file) for e.g.
But I don't think it's necessary, as building hash is fast.

Python Subprocess controlling output

I have a base python project which can accept other python files and execute them as a sub-process. The base project accepts user input, feeds it to the sub-process which then executes code and returns a value via stdout which is fed back to the user.
In the base program I'm doing something similar to:
dataReturnValue = subprocess.check_output(['python', pythonScriptPath, json.dumps(inputParams)])
then in the subprocess I have something like this:
inputParams = sys.argv[1]
...
...
sys.stdout.write(returnValue)
The data is correctly returned, but what I'd like to do is have the data returned be limited to the returnValue. Right now it returns all print statements throughout the subprocess plus the return value. This makes sense to me since it's a form of output and print is akin to a stdout wrapper, but I'd like to better control this.
Is there a way to clear the stdout buffer just prior to my final output statement so that there are no stray prints or outputs included in the value returned from the sub-process?
Edit: I've tried doing a sys.stdout.buffer.flush(), sys.stdout.flush() just prior to the final call in hopes that it would clear out the buffer but the print statements prior still appear to be sent with the final return value.
Try this:
import sys
import os
# Your code here
with open(os.devnull, 'w') as sys.stdout:
# Code that you don't want to be printed here
sys.stdout = sys.__stdout__
# Your code here
Edit:
I even made it into a decorator for you
import sys
import os
def silence(func, *args, **kwargs):
def wrapper(*args, **kwargs):
with open(os.devnull, 'w') as sys.stdout:
result = func(*args, **kwargs)
sys.__dict__['stdout'] = sys.__stdout__
return result
return wrapper
Use it on any function like this:
def test1():
print("TEST1")
#silence
def test2():
print("TEST2")
def test3():
print("TEST3")
test1()
test2()
test3()
Output:
TEST1
TEST3
this might not be the answer you are looking for, but perhaps this is a possible workaround:
dataReturnValue = dataReturnValue.split("\n")[-1]
May be this can help you.
You can use subprocess Popen,PIPE to do your task.if you wish to use multiple subprocess instances here is the link
Python subprocess: how to use pipes thrice?
How to control the output ?
below command(dummy command) will generate 100 of lines , but i need only one line which have text 'Appium Started'
from subprocess import Popen,PIPE
command='appium-p 4723'
p1=Popen(command,stdout=Pipe)
return_value= 'Started Appium'
#this will store the output which command generated
output = p3.communicate()[0]
for line in output:
if returnvalue in line:
print line
else:
pass
in the end you only get the line which you wanted i.e. Appium Started

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.

Python calling function inside other function not working

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.

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)

Categories