How can i call the function from main event into another method? - python

i just confused, how can i call the function into another method? here's the script.
def createTargetCamera(path):
src = initArguments()
return
if __name__ == '__main__':
#read argparse
args = initArguments()
print (args.conf)
cam = createTargetCamera(args)
print (cam)
i want to call the variabel args into createTargetCamera() method. can some one please help me?

you forgot to return the value:
def createTargetCamera(path):
src = initArguments() # can be replace by src = path
return src
if __name__ == '__main__':
#read argparse
args = initArguments()
print (args.conf)
cam = createTargetCamera(args)
print (cam)
Also, if "args", "path" and "src" are equal to initArguments(), you can avoid some of them.

Related

problem about Parameter transfer of jsonpath

I am running a code like below, but it's not what I want. real_path is defined at def check, so it's static.
#code before change
def check(path):
with open(path,'r', encoding="utf-8") as f:
file=json.load(f)
real_path='C:\\Documents and Settings\\Administrator\\Local Settings\\Temp\\5.exe'
call = jsonpath(file,"$.behavior.processes[?(#.process_path==real_path)].calls[?(#.category=='network')]")
print(call)
if __name__ == "__main__":
path="C:/users/hdl/Desktop/2min/2-5.json"
#real_path = 'C:\\Documents and Settings\\Administrator\\Local Settings\\Temp\\5.exe'
check(path)
Then I have changed like below, I have defined the real_path at main, thus it has worked.
def check(path):
with open(path,'r',encoding="utf-8") as f:
file=json.load(f)
#real_path='C:\\Documents and Settings\\Administrator\\Local Settings\\Temp\\5.exe'
call = jsonpath(file,"$.behavior.processes[?(#.process_path==real_path)].calls[?(#.category=='network')]")
print(call)
if __name__ == "__main__":
path="C:/users/hdl/Desktop/2min/2-5.json"
real_path = 'C:\\Documents and Settings\\Administrator\\Local Settings\\Temp\\5.exe'
check(path)
Does somebody know why?
What if I want to define at def check, what should I do?

Execute method from another python file with argues

I'm a python begginer and I wanted to execute a method (A) with argues that will call another method (B) that will return values to (A).
I only can't reached the (B) method directly, for this I used a main. And so I can't retrieve (B)'s informations from (A)
My architecture looked like this :
Main Folder
|-> test_caller.py (A)
|-> called_file.py (B)
I want to call a method with argues from test_caller.py (main method), that will execute method to called_file.py (function_called()), and I want that function_called() method return flag or value if it's possible.
test_caller.py :
import sys
import subprocess
import os
def main():
#method can't return something
# my_path = os.path.join(os.path.abspath(__file__+"/../"),"test.py")
# script_descriptor = open(my_path)
# a_script = script_descriptor.read()
# sys.argv = [my_path, "variable1","https://google.com"]
# exec(a_script)
my_path = os.path.join(os.path.abspath(__file__+"/../"),"test.py")
#call function tes.py, but need a main method and so doesn't return the function value yet
test = subprocess.run(['python',my_path,"variable1","https://google.com"],check=True)
print(test)
if __name__ == '__main__':
main()
called_file.py :
import sys
import requests
def function_called(variable,variable2):
#Potato = Flag
try :
potato = 0
print(str(variable + " is ready to use "+ variable2 + " as variable number 2"))
request = requests.get(variable2)
if(request.status_code == 200):
response = request.text
return response
else :
potato = 1
#Flag exception potato = 1 => failure
except Exception as exc :
print("An error occured " + str(exc))
potato = 1
return potato
#I want that main issue disappear, for returning potato method value (flag 0 or 1) to my method's calling
# if __name__ == "__main__":
# function_called(sys.argv[1],sys.argv[2])
How could I do that ? Thanks for helping me.
Hello AKX thanks for your help, this solution might be good for our program,
For those who's had a similar problem, the solution now is this:
on test_caller.py :
def main():
test = importlib.import_module("called_file")
object = test.function_called("tata","https://www.google.com")
print(object) #do what you want from the returned object

Can't run multiple functions in a main function in Python

So a problem I'm facing is this:
I defined 2 functions and one function uses the variable of the other function
Now when I run both of them using the following code, it works properly:
def type_anything():
use = input(">")
return use
def print_it():
print(use)
if __name__ == '__main__':
while True:
use = type_anything()
print_it()
Output:
> abcd
abcd
> efgh
efgh
> anything
anything
But when I decide to make a main function that will run both the above functions and then run the main function under the "if __name__ == ......" line, something like this:
def type_anything():
use = input("> ")
return use
def print_it():
print(use)
def run_it():
while True:
use = type_anything()
print_it()
if __name__ == '__main__':
run_it()
The program doesn't run properly instead shows this error:
> anything
Traceback (most recent call last):
File "C:/<location>/sample.py", line 17, in <module>
run_it()
File "C:/<location>/sample.py", line 13, in run_it
print_it()
File "C:/<location>/sample.py", line 7, in print_it
print(use)
NameError: name 'use' is not defined
Why is this happening? What do I need to do?
This should solve your problem:
def type_anything():
use = input("> ")
return use
def print_it(use):
print(use)
def run_it():
while True:
use = type_anything()
print_it(use)
if __name__ == '__main__':
run_it()
The print_it function is not aware of any variable use hence the error.
Noticed how the type_anything function returns the variable use and the print_it function accepts an argument and then prints that.
Please do not get into the habit of using global variables, in the long run these will break everything you write. This is just an example to help you with your understanding of the problem!
Your problem is variable scope. In the first example your variable use is global because you define it in the main program:
if __name__ == '__main__':
while True:
use = type_anything()
print_it()
It is not defined in type_anything, you could rename this variable to whatever and it would still work:
def type_anything():
x = input(">")
return x
In the second example you define it in a function:
def run_it():
while True:
use = type_anything()
print_it()
You could fix this by making use a global variable:
def run_it():
global use
while True:
use = type_anything()
print_it()
A much better way of doing this
Pass the variable use to the function that uses it:
def print_it(use):
print(use)
def run_it():
while True:
use = type_anything()
print_it(use)
You can't use a variable defined in one function in another function.
Each function needs to receive the arguments it uses.
def type_anything():
use = input(">")
return use
def print_it(use):
print(use)
if __name__ == '__main__':
while True:
use = type_anything()
print_it(use)

How to use a list in other function?

I have a list like this cs_id["CS_A1","CS_b7",...] in a function. At the end of the function the list ist filled with 80 values. How can I use this list (and values) in another function? Here I want to use the list cs_id[] from function unzip in function changecs. (By the way, the second function isn't ready yet.)
Update
I still dont get it....dont know why.
Here is my full code...maybe someone can help.
maker.py
#!/usr/bin/python
import getopt
import sys
import functions as func
ifile = ''
ofile = ''
instances = 0
def main(argv):
try:
opts, args = getopt.getopt(argv, "hi:o:n:d", ["help", "ifile=", "ofile=", "NumberOfInstances="])
except getopt.GetoptError:
func.usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
func.usage()
sys.exit()
elif opt in '-d':
global _debug
_debug = 1
elif opt in ("-i", "--ifile"):
global ifile
ifile = arg
elif opt in ("-o", "--ofile"):
global ofile
ofile = arg
elif opt in ("-n", "--NumberOfInstances"):
global instances
instances = int(arg)
func.unzip(ifile, instances)
func.changecs()
if __name__ == "__main__":
main(sys.argv[1:])
functions.py
import os
import zipfile
import sys
import string
import random
# printing usage of warmaker.py
def usage():
print "How to use warmaker.py"
print 'Usage: ' + sys.argv[0] + ' -i <inputfile> -o <outputfile> -n <NumberOfInstances>'
# creating random IDs for CS instance e.g. CS_AE, CS_3B etc.
def id_generator(size=2, chars=string.ascii_uppercase + string.digits):
return ''.join(random.choice(chars) for _ in range(size))
# unzip the reference warfile and build n instances
def unzip(ifile, instances,):
newinstance = ifile
cs_id = []
for i in xrange(instances):
cs_id.append('CS_' + id_generator())
i += 1
print 'Searching for reference file ' + newinstance
if os.path.isfile(newinstance): # check if file exists
print 'Found ' + newinstance
else:
print newinstance + ' not fonund. Try again.'
sys.exit()
print 'Building ' + str(instances) + ' instances... '
for c in xrange(instances):
extract = zipfile.ZipFile(newinstance)
extract.extractall(cs_id[c])
extract.close()
print cs_id[c] + ' done'
c += 1
return cs_id
#def create_war_file():
def changecs(cs_id):
n = 0
for item in cs_id:
cspath = cs_id[n] + '/KGSAdmin_CS/conf/contentserver/contentserver-conf.txt'
if os.path.isfile(cspath):
print 'contentserver-conf.txt found'
else:
print 'File not found. Try again.'
sys.exit()
n += 1
#f = open(cspath)
#row = f.read()
Two ways.
1/ Return the list in unzip
def unzip(ifile, instances):
# No need for this global
# global cs_id
cs_id = []
# Do stuff
# [...]
# Return the list
return cs_id
In this case you can call unzip and get the complete list as return value:
def changecs(instances):
# The following line is equivalent to
# cs_id = unzip(ifile, instances)
# for c in cs_id:
for c in unzip(ifile, instances):
cspath = cs_id + '/abc/myfile.txt'
2/ Pass it as a parameter and modify it in unzip.
def unzip(ifile, instances, cs_id):
# Do stuff
# [...]
In this case you can pass unzip the empty list and let it modify it in place:
def changecs(instances):
cs_id = []
unzip(ifile, instances, cs_id):
for c in cs_id:
cspath = cs_id + '/abc/myfile.txt'
I prefer the first approach. No need to provide unzip with an empty list. The second approach is more suited if you have to call unzip on an existing non-empty list.
Edit:
Since your edit, unzip returns cs_id and changecs uses it as an input.
def unzip(ifile, instances,):
[...]
return cs_id
def changecs(cs_id):
[....]
But you call them like this:
func.unzip(ifile, instances)
func.changecs() # This should trigger an Exception since changecs expects a positional argument
You should call them like this:
variable = func.unzip(ifile, instances)
func.changecs(variable)
or just
func.changecs(func.unzip(ifile, instances))
One possibility is to initialize the list outside of the function, then call it in both, i guess.
you can call the function and return it to the other function. Not sure where you'd want to use it but as an example this is the same concept
def foo():
l = [1,3,2,5,4,6,5]
l.append(10)
return l
def bar():
l = foo()
print (l)
return terminates the function and in your case you'd want to put it at the end of the function.
Make unzip return the value. Call unzip from the main block. Then pass the return value from unzip into changecs. Simple.
def unzip(...):
...
return cs_id
def changecs(cs_id, ...):
... do stuff with cs_id ...
if __name__ == "__main__":
... main block ... # This can be replaced with any kind of driver code
Alternatively, you can call unzip directly from within changecs (if that flow is permissible).
The code is all but there. At the bottom of def unzip() the array cs_id is being returned using the return command. The returned array can be stored in a variable from the function which runs unzip(). In this case, it's our main python function.
After you have the cs_id array in a variable in your main function, pass it to changecs() like: func.changecs(cs_id)
Edit last two lines of def main(argv) to:
cs_id = func.unzip(ifile, instances)
func.changecs(cs_id)
In the above code, unzip(ifile, instances) returns our array cs_id. We pass this into changecs(cs_id) as an parameter.

2 responses from 2 functions into new function

I'm current writing a short bit of code that will compare an etag for a web server page in a saved document to the etag on the server. If they are different, the code will indicate this. My code is below:-
import httplib
def currentTag():
f = open('C:/Users/ME/Desktop/document.txt')
e = f.readline()
newTag(e)
def newTag(old_etag):
c = httplib.HTTPConnection('standards.ieee.org')
c.request('HEAD', '/develop/regauth/oui/oui.txt')
r = c.getresponse()
current_etag = r.getheader('etag').replace('"', '')
compareTag(old_etag, current_etag)
def compareTag(old_etag, current_etag):
if old_etag == current_etag:
print "the same"
else:
print "different"
if __name__ == '__main__':
currentTag()
Now, reviewing my code, there is actually no reason to pass 'etag' from the currentTag() method to the newTag() method given that the pre-existing etag is not processed in newTag(). Nonetheless, if I don't do this, how can I pass two different values to compareTag(). So for example, when defining compareTag(), how can I pass 'etag' from the currentTag() method and 'current_etag' from the newTag() method?
you shouldn't chain your function calls like that, have a main block of code that calls the functions serially, like so:
if __name__ == '__main__':
currtag = currentTag()
newtag = newTag()
compareTag(currtag,newtag)
adjust your functions to return the relevant data
the basic idea of a function is that it returns data, you usually use functions to do some processing and return a value and not for control flow.
change your main to:
if __name__ == '__main__':
compareTag(currentTag(), newTag())
and then have currentTag() return e and newTag() return current_etag
def checkTags():
c = httplib.HTTPConnection('standards.ieee.org')
c.request('HEAD', '/develop/regauth/oui/oui.txt')
r = c.getresponse()
with open('C:/Users/ME/Desktop/document.txt', 'r') as f:
if f.readline() == r.getheader('etag').replace('"', ''): print "the same"
else: print "different"
you could make the variables (i.e. etag) global

Categories

Resources