problem about Parameter transfer of jsonpath - python

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?

Related

Calling functions defined within a class - NameError: name 'filename' is not defined [duplicate]

This question already has answers here:
Class NameError: name 'var' is not defined [duplicate]
(3 answers)
Closed 1 year ago.
I am new to python and am struggling with classes. Here is my code.
class sgrid(filename):
def __init__(filename):
filename = self.filename # do I need these?
print_to_app2 = self.print_to_app2 # do I need these?
def print_to_app2(text):
print(text)
def iterate(filename):
self.print_to_app2(filename)
self.print_to_app2('Application is initializing')
if __name__ == '__main__':
sgrid=sgrid()
filename = "a_file_name"
sgrid.iterate(filename)
I get this error: NameError: NameError: name 'filename' is not defined
What am I doing wrong? I want to be able to call functions within this class and outside it.
Like that filename is the superclass of your class sgrid.
But there's no class called filename, so the it's not found.
And you have to pass the self reference to all your methods.
I'm not so sure what you want to do, but if you want to create a sgrid with a filename and print_to_app2 the filename, you could try sth like this:
class sgrid:
def __init__(self, filename):
self.filename = filename
def print_to_app2(self, text):
print(text)
def iterate(self):
self.print_to_app2(self.filename)
self.print_to_app2('Application is initializing')
if __name__ == '__main__':
filename = "a_file_name"
sgridInstance=sgrid(filename)
sgridInstance.iterate()
There are lots of things that are wrong within this script :)
But the main one described here is at the first line.
class sgrid(filename):
This is where you defined your class, and you're passing as first argument filename, which the program does not know about. You should leave that empty.
There are other errors aswell.
class sgrid():
# I fixed the declaration above.
def __init__(self, filename):
self.filename = filename
def iterate(self, filename=None):
if filename is None:
filename = self.filename
print("App is initializing")
print(filename)
if __name__ == '__main__':
sgrid=sgrid() # this will produce an error, i leave that up to you
# PS : are you sure you want to name this variable "sgrid" ? :)
filename = "a_file_name"
sgrid.iterate(filename)
The first positional argument of your methods is passed by default to the function when you call a class. And you need to indicate it when you declare the function, the name of this variable is self. This is a variable that will hold values that you can share between methods in your class.
I have fixed a few other errors aswell. I invite you to read the code, ask questions and maybe look at documentations. :)
You may want to this :
class sgrid(object):
def __init__(self,filename):
self.filename = filename # do I need these?
def print_to_app2(self,text):
print(text)
def iterate(self):
self.print_to_app2(self.filename)
self.print_to_app2('Application is initializing')
if __name__ == '__main__':
filename = "a_file_name"
sgrid=sgrid(filename)
sgrid.iterate()
class sgrid:
def __init__(self , filename):
filename = self.filename
def print_to_app2(text):
print(text)
def iterate(filename):
self.print_to_app2(filename)
self.print_to_app2('Application is initializing')
if __name__ == '__main__':
sgrid=sgrid()
filename = "a_file_name"
sgrid.iterate(filename)

Python unittest a module instead of a function

I'm trying to write a test.py file to test a module I wrote. The specifications of the program are that I take serial user input and then print, not return a single answer. The first line of user input indicates how many inputs will follow. With an example program, "4\n1\n2\n3\n4\n" would mean there are 4 inputs and the inputs are [1,2,3,4]. Here is an example of the program that would take the input (sumEx.py):
import sys
def sum():
n = int(sys.stdin.readline().strip())
nums = []
for _ in range(n):
nums.append(int(sys.stdin.readline().strip()))
result = 0
for num in nums:
result += num
print(result)
if __name__ == "__main__":
sum()
I realize that in this example the for loop is redundant, but this is just an example for the actual program I am working on to abstract the problem. Currently, this is the test file I have:
from io import StringIO
import sys
from _pytest.monkeypatch import MonkeyPatch
import unittest
from sumEx import sum as program
class Testing(unittest.TestCase):
def test_string(self):
monkeypatch = MonkeyPatch()
monkeypatch.setattr('sys.stdin', StringIO("8\n1\n2\n3\n4\n5\n6\n7\n8\n"))
self.assertEqual(program(), 36)
def test_boolean(self):
monkeypatch = MonkeyPatch()
monkeypatch.setattr('sys.stdin', StringIO("4\0\n1\n2\n3\n"))
self.assertEqual(program(), 6)
if __name__ == '__main__':
unittest.main()
The problem is that my tests will only work if I returned them instead of printing them. Ideally, my test file would call the file sumEx.py and then
if __name__ == "__main__":
sum()
would call the sum function, the test would supply the input (like an actual person typing each line), and then whatever sum prints would be considered the output for the test. Any help is greatly appreciated. Please ask any questions if something is too vague. Thank you!
If anyone is curious, this is what I'm gonna go with for now. This takes input from a file and mimics user input through sys.stdin. It then reads the correct output from a file and compares it to the output of the program. It also runs the same test case with different inputs with the help of parameterization. Thank you #MrBeanBremen for the suggestion!
class Testing(unittest.TestCase):
def load_file(self, fileName, inOut):
try:
inputFile = open(fileName, 'r')
fileInput = r'{}'.format(inputFile.readline())
for line in inputFile.readlines():
fileInput = r'{}'.format(fileInput + line)
if inOut == 'in':
fileInput = r'{}'.format(fileInput+'\n')
inputFile.close()
return fileInput
except:
print("ERROR LOADING FILE")
#parameterized.expand([
["./tests/test0in.txt", "./tests/test0out.txt"],
["./tests/test1in.txt", "./tests/test1out.txt"],
["./tests/test2in.txt", "./tests/test2out.txt"]])
#patch('sys.stdout', new_callable=StringIO)
def test(self, inputFile, outputFile, mock_stdout):
monkeypatch = MonkeyPatch()
monkeypatch.setattr('sys.stdin', StringIO(self.load_file(inputFile, "in")))
program.main()
self.assertEqual(mock_stdout.getvalue(), self.load_file(outputFile, "out"))
if __name__ == '__main__':
unittest.main(verbosity=2)

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 can i call the function from main event into another method?

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.

Calling Functions in Main Function

I've written a program and want to call the functions in the main. However, I've been receiving a SyntaxError. I'm not sure what I'm doing wrong. Here is my code, I've tried a few things but the main function won't call the rest of the functions.
class Matrix(object):
def open_file():
'''Opens the file if it exists, otherwise prints out error message'''
Done = False
while not Done:
try:
File = input("Enter a filename: ").lower() #Asks user for a file to input
Open_File = open(File, "r") #Open the file if it exists and reads it
Info = Open_File.readlines()[1:]
Open_File.close() #Close the file
Done = True #Exits the while loop
except FileNotFoundError:
print("Sorry that file doesn't exist!") #prints out error message if file doesn't exist
return Info #Info is the file_pointer(fp)
def __init__(self): # This completed method is given
'''Create and initialize your class attributes.'''
self._matrix = {} #Intialize the matrix
self._rooms = 0 #Set the rooms equal to zero
def read_file(self, Info): #Info is equvalient to the file pointer or fp
'''Build an adjacency matrix that you read from a file fp.'''
self._rooms = Info.readline()
self._rooms = int(self._rooms)
for line in Info:
a, b = map(int, line.split())
self._matrix.setdefault(a, set()).add(b)
self._matrix.setdefault(b, set()).add(a)
return self._rooms and self._matrix
def __str__(self):
'''Return the adjacency matrix as a string.'''
s = str(self._matrix)
return s #__str__ always returns a string
def main(self):
matrix = Matrix()
info = matrix.open_file()
matrix.read_file(info)
s = str(matrix)
print(s)
if __name__ == '__main__':
m = Matrix()
m.main()
A few things:
it's self.read_file, not just read_file. It's an instance method so you need to use self.
Same for __init__(self), you need to call self.__init__. Although typically you don't do this manually. You would "instantiate" the class via Matrix().
You can't assign to a function call, so open_file() = Info simply doesn't make sense. Perhaps you mean info = open_file().
It looks like you're a little confused about how to lay out your class. Try leaving main outside of the class, like this (untested):
def main:
matrix = Matrix()
info = matrix.open_file()
matrix.read_file(info)
s = str(matrix)
print(s)
You will also need to dedent if __name__ == '__main__' to the global scope.
Ideally you may want to write something like below. Also, your open_file() has to be rewritten.
class Matrix(object):
def open_file(self):
File = input("Enter a filename: ").lower() #Asks user for a file to input
fp = open(File, "r")
return fp
#### Your matrix class code goes here
def main():
myMatrix = Matrix()
fp = myMatrix.open_file()
ret = myMatrix.read_file(fp)
print(myMatrix)
if __name__ == "__main__":
main()
There is an error in your program's entry. ' if name == 'main':'shouldn't be included in a Class. It should be global. And another, you want to call a member function of Matrix, but where is the object of Matrix. The code below is correct:
Class Matrix(object):
#################
your codes
#################
if __name__ == '__main__':
m = Matrix()
m.main()
the way this is posted
if __name__ == "__main__":
main()
is going to be executed when the class is defined -- not when the program is run. As written, the class won't have been instantiated so there's no Matrix object on which you can call main().
You'll need to move the call out one indent, so it is aligned with the class definition, and then create an object before calling its main():
if __name__ == "__main__":
instance = Matrix()
instance.main()
You've also got the assignments backwards in main(). It should read more like this:
info = open_file()
self.read_file(Info)
s = __str__(self)
print(s)
the open_file() method also has some issues. You want to create Info outside the scope of your loop so you know you've got it to return. Your comment indicates the Info is supposed to be the file pointer -- but it's not, as you wrote it. Open_File is the file pointer, and Info is the content of the file (at least, everything but the first line). Unless you're expecting a huge amount of data, it's probably easier to pass the contents -- or to combine open_file and read_file into the same function.
You also want to use the usual python pattern for opening and closing the files the with context manager - that will close your file for you.
Heres a quick and dirty version of Open_file and Read_file in one package.
def read_file(self):
#get the filename first
filename = None
while not filename:
user_fn = input("Enter a filename: ").lower()
if os.path.exists(user_fn):
filename = user_fn
else:
print ("Sorry that file doesn't exist!")
# 'with' will automatically close the file for you
with open(filename, 'rt') as filepointer:
# file objects are iterable:
for line in filepointer:
a, b = map(int, line.split())
self._matrix.setdefault(a, set()).add(b)
self._matrix.setdefault(b, set()).add(a)
I'm not clear what self._matrix.setdefault(a, set()).add(b) is supposed to be doing for you here, but in syntactic terms you can simply the structure to "get the filename, open with with, iterate over it"

Categories

Resources