I have written a simple python script to hash a file and output the result. However, when I run the script (python scriptname.py), I don't get any output (expected it to print the checksum). I don't get any errors from the console either.
What am I doing wrong?
#!/usr/bin/env python
import hashlib
import sys
def sha256_checksum(filename, block_size=65536):
sha256 = hashlib.sha256()
filename = '/Desktop/testfile.txt'
with open(filename, 'rb') as f:
for block in iter(lambda: f.read(block_size), b''):
sha256.update(block)
return sha256.hexdigest()
def main():
for f in sys.argv[1:]:
checksum = sha256_checksum(f)
print(f + '\t' + checksum)
if __name__ == '__main__':
main()
def main():
for f in sys.argv[1:]:
The script expected arguments. If you run it without any arguments you don't see any ouput.
The main body suppose that you provide list of files for hashing but in hashing function you hardcoded
filename = '/Desktop/testfile.txt'
So, if you want to pass files for hashing as script arguments remove the line
filename = '/Desktop/testfile.txt'
and run
python scriptname.py '/Desktop/testfile.txt'
Related
Within my code I am attempting to import modules written by myself. Said modules interact with files on the system, either encrypting, decrypting or removing them altogether. When trying to import these modules I receive the below:
FileNotFoundError: [Errno 2] No such file or directory: <Directory>
Oddly this error seems to appear before anything local within the file runs (calls are at the end), making me believe python is parsing the files during the import phase and not find the files (apologies but I am novice when it comes to importing self created stuff)
Below is one of the methods I am importing (also the one flagging the error)
import urllib.request, re, os
def getKey(url, path):
urllib.request.urlretrieve(url, 'C:\\code\\'+path)
def readFiles(keyFile, targetFile, outfile):
infile = keyFile # read in the input file name
infd = open('C:\\code\\'+infile,"r") # open the file and create the file descriptor infd
key = infd.read( )
key = key.strip('\n')
#print('key= '+key)
infile = targetFile
infd = open('C:\\code\\'+infile, "r")
ptext = infd.read( ).strip('\n')
infd.close
xor(outfile, ptext, key)
def xor(outfile, ptext, key):
outfd = open('C:\\code\\'+outfile, "w")
pLength = len(ptext)
#get the length of the plaintext and cut the key into the same size
keyChunks = [key[i:i+pLength] for i in range(0, len(key), pLength)]
i = 0
while i < len(keyChunks):
a = int(ptext)
b = int(keyChunks[i])
out = a ^ b
i=i+1
outfd = open('C:\\code\\'+outfile, "w")
outfd.write(str(out))
outfd.close
def cleanup(targetFile):
os.remove(targetFile)
def enc():
outfile = 'affk.xor'
getKey('http://192.168.56.10/sym.key', 'sym.key')
readFiles('sym.key', 'affk.txt', outfile)
cleanup('C:/code/affk.txt')
def dec():
outfile = 'affk.txt'
getKey('http://192.168.56.10/sym.key', 'sym.key')
readFiles('sym.key', 'affk.xor', outfile)
cleanup('C:/code/affk.xor')
cleanup('C:/code/sym.key')
enc()
#dec()
Below is a snippet of my main file with the imports and calling function
import os, math, affine, re, urllib.request, ctypes
from xor import enc
from rsa1 import run
---Additional Code here---
def main():
# Call function to search for the files we want to encrypt
search()
# Call function to read the target files. Main ciphers are daisy chained off reader function
reader(targets)
# Call function to XOR Affine cipher key
xor.enc()
# Call function to encrypt key used for above XOR using RSA
rsa1.run()
Any assistance with this problem would be greatly appreciated! Apologies if this is an extremely dumb question!
I have created a python program, see below. It moves files to AWS S3. It it is expecting input. It works well with pycharm but when I call the python script from command prompt, it doesn't take the input value. Here is my code:
import os
import sys
import boto3
from botocore.client import Config
import configparser
import re
import os.path
## Initialize the Parameters
def initconfig(input):
config = configparser.ConfigParser()
config.read_file(open( 'CONFIG_AIRBILLING.conf'))
print('Code Name is :'+ input)
global REMOTE_DIR,ACCESS_KEY_ID,ACCESS_SECRET_KEY,BUCKET_NAME,TARGET_DIR,FILENAME,SRC_DIR,data,File
ACCESS_KEY_ID = config.get('ACCESS', 'ACCESS_KEY_ID')
print('ACCESS_ID_IS:'+ ACCESS_KEY_ID)
ACCESS_SECRET_KEY = config.get('ACCESS', 'ACCESS_SECRET_KEY')
BUCKET_NAME = config.get('ACCESS', 'BUCKET_NAME')
SRC_DIR = config.get(input, 'SRC_DIR')
FILENAME = config.get(input, 'FILENAME')
#LOC="C:\test\demo.txt"
TARGET_DIR = config.get(input, 'TARGET_DIR')
File='demo.txt'
#data = open(File, 'rb') ## This is the filename, need to change it
## This function will make sure file exist in Source directory
def readstatus():
try:
with open(File,'r') as f:
f.closed
result='True'
movefiles(result)
except (Exception,FileNotFoundError) as e:
print('***Error:File Not Found or Accessible***')
result='False*'
raise e
## This function will move the files to AWS S3 bucket
def movefiles(result):
if result=='True':
s3 = boto3.resource(
's3',
aws_access_key_id=ACCESS_KEY_ID,
aws_secret_access_key=ACCESS_SECRET_KEY,
config=Config(signature_version='s3v4')
)
s3.Bucket(BUCKET_NAME).put_object(Key=TARGET_DIR + '/' + File, Body=File)
print('***File Moved***')
print("Done")
initconfig("ABC")
readstatus()
The code above runs fine with pycharm because I can change the value of initconfig function value. But when I run this through command prompt, it doesn't take the parameter values I pass. Here is how I am passing the value, Please help me to fix this.
From Command Prompt
python move_files_to_S3 "TEST"
You want sys.argv, which is a list with all parameters passed through the command line (but notice sys.argv[0] is the name of the script itself).
You'd also do good to check for __name__ == '__main__' to distinguish between when your code is called from the python interpreter through the command line (as in your example at the end of your post) and when it is imported from another module:
if __name__ == '__main__':
initconfig(sys.argv[1])
readstatus()
I'm trying to run the following python code for to exercise
#!/bin/python3
import os
import sys
#
# Complete the maximumDraws function below.
#
def maximumDraws(n):
return n+1
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
t = int(input())
for t_itr in range(t):
n = int(input())
result = maximumDraws(n)
fptr.write(str(result) + '\n')
fptr.close()
but i get this error message
Traceback (most recent call last):
File "maximumdraws.py", line 13, in <module>
fptr = open(os.environ['OUTPUT_PATH'], 'w')
File "/home/inindekikral/anaconda3/lib/python3.6/os.py", line 669, in __getitem__
raise KeyError(key) from None
KeyError: 'OUTPUT_PATH'
My Operation System is Linux Mint 19 Cinnamon.
What i have to do?
I'm sure there are other ways to do this, but for Hackerrank exercises, the file pointer was opened this way:
fptr = open(os.environ['OUTPUT_PATH'], 'w')
... and I want it to just go to standard output.
I just changed that line to
fptr = sys.stdout # stdout is already an open stream
and it does what I want.
Note that on the one hand, os.environ['OUTPUT_PATH'] is a string, while fptr is a stream/file pointer.
Variations:
If you want to write to a file, you can do it the way suggested above (setting the OUTPUT_PATH environment variable).
Or, you can set the os.environ directly in python, e.g.
os.environ['OUTPUT_PATH'] = 'junk.txt' # before you open the fptr!
os.environ lets you access environment variables from your python script, it seems you do not have an environment variable with name OUTPUT_PATH. From the terminal you run your python script, before running your python code set an environment variable with name OUTPUT_PATH such as:
export OUTPUT_PATH="home/inindekikral/Desktop/output.txt"
Your python script will create a file at that location.
A KeyError means that an element doesn’t have a key. So that means that os.environ doesn’t have the key 'OUTPUT_PATH'.
Simply, change the path of the python code to your local path.
fptr = open("./result.output", 'w')
Hackerrank sends output to a file, but for practice locally, the output can be printed.
You can remove the use of ftpr by commenting out these lines
fptr = open(os.environ['OUTPUT_PATH'], 'w') and
fptr.close()
And replace line fptr.write(str(result) + '\n') with print(str(result) + '\n')
change your code like this:
if __name__ == '__main__':
t = int(input())
for t_itr in range(t):
n = int(input())
result = maximumDraws(n)
print(str(result) + '\n')
This is my test code, but I have a more elaborate one - but they both don't work. In python 3.x.
import sys
def main():
inputfile = 'hi'
print(inputfile)
if __name__ == '__main__':
main()
EDIT: This what I want to use the terminal for (and syntax errors - same problem):
import csv
import sys
import json
inputfile = sys.argv[1]
outputfile = sys.argv[2]
# reading the csv
with open(inputfile, 'r') as inhandle: # r is reading while w is writing
reader = csv.DictReader(inhandle)
data = []
for row in reader:
data.append(row)
print(data)
# writing the json
with open(outputfile, "W") as outhandle:
json.dump(data, outhandle, indent=2)
As far as I understood by the code you've attached, hi must be wrote as 'hi'. In your original code, hi is regarded as another variable being assigned to inputfile, but it's not defined yet.
how to create file names from a number plus a suffix??.
for example I am using two programs in python script for work in a server, the first creates a file x and the second uses the x file, the problem is that this file can not overwrite.
no matter what name is generated from the first program. the second program of be taken exactly from the path and file name that was assigned to continue the script.
thanks for your help and attention
As far as I can understand you, you want to create a file with a unique name in one program and pass the name of that file to another program. I think you should take a look at the tempfile module, http://docs.python.org/library/tempfile.html#module-tempfile.
Here is an example that makes use of NamedTemporaryFile:
import tempfile
import os
def produce(text):
with tempfile.NamedTemporaryFile(suffix=".txt", delete=False) as f:
f.write(text)
return f.name
def consume(filename):
try:
with open(filename) as f:
return f.read()
finally:
os.remove(filename)
if __name__ == '__main__':
filename = produce('Hello, world')
print('Filename is: {0}'.format(filename))
text = consume(filename)
print('Text is: {0}'.format(text))
assert not os.path.exists(filename)
The output is something like this:
Filename is: /tmp/tmpp_iSrw.txt
Text is: Hello, world