I've got this piece of code that calculates both the MD5 and SHA1 value of a given file and presents it in the console. It does its job, however i get the error message:
Traceback (most recent call last):
File "C:\Program Files (x86)\Aptana\workspace\Ipfit5\Semi-Definitief\test6.py",
line 64, in <module>
hash_file(woord)
File "C:\Program Files (x86)\Aptana\workspace\Ipfit5\Semi-Definitief\test6.py",
line 29, in hash_file
hash_file(sys.argv[1]);
IndexError: list index out of range
the code looks as following:
import sys, hashlib, os
def hash_file(filename): #Calculate MD5 and SHA1 hash values of a given file
# Create hash objects for MD5 and SHA1.
md5_hash = hashlib.md5()
sha1_hash = hashlib.sha1()
filename = r"C:/this.png"
# Read the given file by 2K blocks. Feed blocks
# into into the hash objects by "update(data)" method.
fp = open(filename,'rb')
while 1:
data = fp.read(2048)
if not data:
break
else:
md5_hash.update(data)
sha1_hash.update(data)
fp.close()
print "The MD5 hash of your file is"
print filename,":", md5_hash.hexdigest();
print "The SHA1 hash of your file is"
print filename,":", sha1_hash.hexdigest();
if __name__ == '__main__':
hash_file(sys.argv[1]);
hash_file(woord)
I call the function for (woord) because that is something defined later on in the script, but it is basically the same image as filename in the function hash_file(filename).
Why do i get this error when it does show me both the hash values and how do i get rid of it ?
EDIT: I know it has somethin to do with the if name == 'main':
hash_file(sys.argv[1]); but i can't figure it out.
Any help is greatly appreciated
There is something wrong with that piece of code, the "if name == 'main':" statement, means that the code inside the "if" only work when the python code is executed and not when it is used as a module.
But inside the "if", a recursive call: hash_file(sys.argv[1]) is used, it means that the code needs an argument, but it will start a infinite recursive loop.
I think that the code:
if __name__ == '__main__':
hash_file(sys.argv[1]);
goes outside the hash_file() function
I think this will work as you want:
import sys, hashlib, os
def hash_file(filename): #Calculate MD5 and SHA1 hash values of a given file
# Create hash objects for MD5 and SHA1.
md5_hash = hashlib.md5()
sha1_hash = hashlib.sha1()
filename = r"C:/this.png"
# Read the given file by 2K blocks. Feed blocks
# into into the hash objects by "update(data)" method.
fp = open(filename,'rb')
while 1:
data = fp.read(2048)
if not data:
break
else:
md5_hash.update(data)
sha1_hash.update(data)
fp.close()
print "The MD5 hash of your file is"
print filename,":", md5_hash.hexdigest();
print "The SHA1 hash of your file is"
print filename,":", sha1_hash.hexdigest();
# other code here
if __name__ == '__main__':
#hash_file(sys.argv[1]);
hash_file(woord)
When running the file, you have to give an extra argument:
$ python myfile.py argument
If you print sys.argv, you will get something like:
['myfile.py`]
But once adding an extra argument, you can get something like:
['myfile.py', 'argument']
And that is what the [1] accesses.
As you know the code more than me, you'll have to figure out what the script is expecting as an argument.
Related
He is the whole code:
import ifcfg
import json
for name, interface in ifcfg.interfaces().items():
# do something with interface
print (interface['device']) # Device name
print (interface['inet']) # First IPv4 found
print (interface['inet4']) # List of ips
print(ifcfg.default_interface())
When I removeprint(ifcfg.default_interface()) the program runs fine.
Here is the error message I get:
Traceback: File "C:\Users\User\PycharmProjects\pythonProject\IFCONFIG.py", line 15, in
print(ifcfg.default_interface())
return Parser(ifconfig=ifconfig)._default_interface(route_output=route_output)
AttributeError: 'WindowsParser' object has no attribute '_default_interface'. Did you mean: 'default_interface'?
From what I was able to gather this is a Windows specific issue. Ifcfg class WindowsParser currently has no method _default_interface.
You can try and write your own here's the path.
C:..\Programs\Python\Python310\lib\site-packages\ifcfg\parser.py
For reference here's the UNUX version of _default_interface in parser.py
def _default_interface(self, route_output=None):
"""
:param route_output: For mocking actual output
"""
if not route_output:
out, __, __ = exec_cmd('/sbin/route -n')
lines = out.splitlines()
else:
lines = route_output.split("\n")
for line in lines[2:]:
line = line.split()
if '0.0.0.0' in line and \
'UG' in line:
iface = line[-1]
return self.interfaces.get(iface, None)
Alternatively use interfaces() this is generally sufficient for most users.
import ifcfg
import json
for name, interface in ifcfg.interfaces().items():
# do something with interface
print (interface['device']) # Device name
print (interface['inet']) # First IPv4 found
print (interface['inet4']) # List of ips
print(ifcfg.interfaces())
Further reading: https://github.com/ftao/python-ifcfg/issues/25
I'm creating a similarity program that calculates the euclidean distance of images, I'm looking for user input so that if they want to use a portion of the code, they can choose so. in that case, a line (specifically 13 in dc2.py) needs to be changed to " ". How can i go about this?
I've attempted using the open function alongside .write, opening a file though open(dc.py).read(), and to no avail.
This converts the image into an array (program dc2.py):
import numpy as np
import imageio
from numpy import array
img = imageio.imread("Machine Screw.jpg")
data = array(img)
with open('test2.txt', 'w') as outfile:
np.savetxt(outfile, data_slice, fmt='%-7.2f')
exec(open("Halfer.py").read())
Here's the failed code to change the previous .py:
inp = input("Want to use halfer?: ")
if inp == 'y':
the_file = open('dc2.py', 'a')
the_file[13].write(' ')
--------------------------------------
I expected:
Process finished with exit code 0
here's what actually happened:
Traceback (most recent call last):
File "C:/Users/User/Desktop/PySimCode/Resources/Ini.py", line 5, in <module>
the_file[13].write(' ')
TypeError: '_io.TextIOWrapper' object is not subscriptable
Thank you for all the help!
Your solution what you want to implement is not too "Pythonic". In my opinion you should import dc2.py file as module to Ini.py script and use parameters based on user-input to manipulate the behavior of dc2.py script.
For example:
dc2.py
import numpy as np
import imageio
import subprocess
from numpy import array
def image_converter(halfer_needed=True):
img = imageio.imread("Machine Screw.jpg")
data = array(img)
with open('test2.txt', 'w') as outfile:
np.savetxt(outfile, data, fmt='%-7.2f')
if halfer_needed:
sp = subprocess.Popen(["python", "Halfer.py"]) # Call Halfer.py script
ret_stdout, ret_stderr = sp.communicate() # These variables contain the STDOUT and STDERR
ret_retcode = sp.returncode # This variable conains the return code of your command
I think you want to call the Halfer.py script if user wants it so I have used the subprocess module to call this script as you can see above. You can see more details and options about this module: https://docs.python.org/3/library/subprocess.html
Ini.py
from dc2 import image_converter # Import your function from "dc2.py" script
inp = str(input("Want to use halfer?: "))
if inp == 'y':
image_converter(halfer_needed=False)
image_converter() # you don't need to define the keyword argument because the default value is True.
Try this:
inp = raw_input("Want to use halfer?: ")
if inp == 'y':
origin_file = open('dc2.py','r').readlines()
the_file = open('dc2.py','w')
origin_file[12] = '\n'
for line in origin_file:
the_file.write(line)
the_file.close()
Some notes I'd like to add:
input reads a block of text and parses it. You should probably always use raw_input.
open does different things, depending on the mode parameter. In my case, I used r for reading, then w for writing. (I don't think there's a way to read and write on the same <open> object). a is append, which only lets you add lines. Read here
To get the contents from an <open>, use .read() or .readlines().
The 13th line is index 12. Also, I changed it to '\n' instead of ' '.
Don't forget to call .close() on your <open> when you are done with it!
Hope this works for you!
You can, but you shouldn't.
You are trying to activate some code based on uer imput, this is doable encapsulating the code in functions, that you can import and axecute based on a condition.
You are trying to achieve this result by reading files and executing them manually, basically you are doing what the Python interpreter should do..
First, you need to chage you modules to something that activates at will, not as soon as the file is loaded, for instance your dc2.py would look like this:
import numpy as np
import imageio
from numpy import array
import Halfer # <- here you import the py file, not open and read
def run(use_halfer):
img = imageio.imread("Machine Screw.jpg")
data = array(img)
with open('test2.txt', 'w') as outfile:
np.savetxt(outfile, data_slice, fmt='%-7.2f')
if use_halfer:
Halfer.run()
..and your Halfer.py file should look like this:
def run():
# ..all your Halfer.py code here inside the run function
..and then your starting point of the script can look like:
import dc2
inp = input("Want to use halfer?: ")
dc2.run(inp == 'y') # <- here you tell dc2 to use halfer or not.
This is a script that generates password dictionary for guessing a password.
I'm getting this error:
Traceback (most recent call last):
File "pass.py", line 19, in <module>
for p in permutations(stuff, x):
NameError: name 'permutations' is not defined
Code:
#!/usr/bin/python
# define the prefix to try since we knew what the password starts with
prefix = ['begin', 'Begin']
# list of sequences to run through
sequences = ['seq1', 'Seq1', 'SEQ1', 'se2', '!', '123', '555', '103', '_']
# open the password file where the dictionary will be saved
newfile = open('mypass.txt', 'w')
# A python3 thing I guess
stuff = list(sequences)
# Generate permutations of the password, starting wth the prefix and then 2 to 6 combos of the "charset"
for i in prefix:
for x in range(2,6):
for p in permutations(stuff, x):
newfile.write(''.join(p) + '\n')
Example output:
beginseq1SEQ1
begin_seq1
Begin_seq1103
This permutations is probably a function from another file or from a package. Probably you are a new python user and have forgotten to state at the top of your code to which file or package you refer. You have to add a line that looks like this, if you import from a file:
from some_code_file.py import some_function
or like this, if you import a package:
import python_package as py_pa
And than your code should work as you have writen it. Or just alter to the form some_function.permutations(stuff,x) or py_pa.permtations(stuff,x)
I am writing a simple python program which allows us to list all video files in a directory and play them according to the user input. However, I am getting an list out of range error while running this code.
Code:
import os
from subprocess import Popen
def processFile(currentDir):
# Get the absolute path of the currentDir parameter
currentDir = os.path.abspath(currentDir)
global list
list=[]
filesInCurDir = os.listdir(currentDir)
# Traverse through all files
for file in filesInCurDir:
curFile = os.path.join(currentDir, file)
# Check if it's a normal file or directory
if os.path.isfile(curFile):
# Get the file extension
curFileExtension = curFile[-3:]
# Check if the file has an extension of typical video files
if curFileExtension in ['avi', 'dat', 'mp4', 'mkv', 'vob']:
# We have got a video file! Increment the counter
processFile.counter += 1
list.append('curFile')
# Print it's name
print(processFile.counter, file)
else:
# We got a directory, enter into it for further processing
processFile(curFile)
if __name__ == '__main__':
# Get the current working directory
currentDir = os.getcwd()
print('Starting processing in %s' % currentDir)
# Set the number of processed files equal to zero
processFile.counter = 0
# Start Processing
processFile(currentDir)
# We are done. Exit now.
print('\n -- %s Movie File(s) found in directory %s --' \
% (processFile.counter, currentDir))
print('Enter the file you want to play')
x = int(input())
path = list[x-1]
oxmp=Popen(['omxplayer',path])
Aha, found your problem.
In processFile, you say
def processFile(currentDir):
# ...
global list
list=[]
# ...
processFile(...)
This means that, whenever you recurse, you are clearing the list again! This means that the processFile.counter number becomes out-of-sync with the actual length of list.
Three notes on this:
Storing variables on a function like processFile.counter is generally frowned upon, AFAIK.
There's no need for a separate counter; you can simply put len(list) to find the number of entries in your list.
To fix the list problem itself, consider initializing the list variable outside of the function or passing it in as a parameter to be modified.
Im trying to read a file using a scanner then have my program print the first line of the file then looping over each other individual line throughout the file and printing them as well. This issue is I cant even get it to print a single line from the first file. And I'm not receiving an error so I cant figure out the issue
import sys
import scanner
def main():
log1 = (sys.argv[1])
log2 = (sys.argv[2])
def readRecords(s):
s = Scanner("log1")
print (log1)
main()
I will go out on a limb here and suggest something like:
import sys
import scanner
def readRecords(log):
s = scanner.Scanner(log)
print s.SomeAttribute
def main():
log1 = (sys.argv[1])
log2 = (sys.argv[2])
readRecords(log1)
readRecords(log2)
main()
Your original code has numerous problems though, least of which you are never calling your readRecords function. You are also never defining/importing Scanner, and you are doing nothing with the s variable that you are assigning to (unless merely creating a Scanner object has the desired side-effect).