Python copy a file from appdata - copy

how do I copy a file that is present in c:/users/robert/appdata/OpenOffice/work.txt from here to the folder where i execute the python script ? and without adding the folder name (robert) in python script?
from shutil import copyfile
copyfile(src, dst)

import getpass,shutil,os
src="C:\Users\%s\AppData\OpenOffice\work.txt" %(getpass.getuser())
dest=os.getcwd()
def copyFile(src, dest):
try:
shutil.copy(src, dest)
print("Done")
# eg. src and dest are the same file
except shutil.Error as e:
print('Error: %s' % e)
# eg. source or destination doesn't exist
except IOError as e:
print('Error: %s' % e.strerror)
copyFile(src,dest)

Related

Libre office configuration file bootstrap.ini corrupt

I am using the libreoffice-convert package to convert a Word file into PDF. But when I try to convert I get this error. How do I fix this? I have installed LibreOffice 7.0.5
Console log is showing this error:
'C:\\Program Files\\LibreOffice\\program\\soffice.exe -env:UserInstallation=file://C:\\Users\\thesa\\AppData\\Local\\Temp\\soffice-10416-bQefydwUfs2F --headless --convert-to .pdf --outdir C:\\Users\\thesa\\AppData\\Local\\Temp\\libreofficeConvert_-10416-v46bO7ljGHRe C:\\Users\\thesa\\AppData\\Local\\Temp\\libreofficeConvert_-10416-v46bO7ljGHRe\\source'
Try this, you will probably need administrator rights.
Locate and copy your orignal file, for example to "bootstrap.ini.org", in the same directory1.
Open the file and replace its contents with this, which is a copy of my file:
[Bootstrap]
InstallMode=<installmode>
ProductKey=LibreOffice 7.0
UserInstallation=$SYSUSERCONFIG/LibreOffice/4
Another option is to re-install or repair the installation.
Note 1: This copy is just in case you need to revert.
//let data = await fs.promises.readFile(path_to_excel_file);
let data = fs.readFileSync(path_to_excel_file)
let pdfFile = await libreConvert(data, '.pdf', undefined);
await fs.promises.writeFile(`${__dirname}/${docName}.pdf`, pdfFile);
res.download(`${__dirname}/${docName}.pdf`)
It will works File.
Even If don't work then follow
below step:
Add this line 14 after instalDir
const installDir = tmp.dirSync({prefix: 'soffice', unsafeCleanup: true, ...tmpOptions});
const posixInstallDir = installDir.name.split(path.sep).join(path.posix.sep);
then Replace commant
let command = `${results.soffice} --headless --convert-to ${format}`;
That's it..
-env:UserInstallation needs to be in URI form.
Note: also that you using file:// this should be file:/// see File URI scheme
-env:UserInstallation=file:///C:/Users/thesa/AppData/Local/Temp/soffice-10416-bQefydwUfs2F
>>> from pathlib import Path
>>> def get_posix(mypath) -> str:
>>> p = Path(mypath)
>>> return p.as_posix()
>>> tmp = "C:\\Users\\thesa\\AppData\\Local\\Temp\\soffice-10416-bQefydwUfs2F"
>>> get_posix(tmp)
'C:/Users/thesa/AppData/Local/Temp/soffice-10416-bQefydwUfs2F'
or
>>> from pathlib import Path
>>> tmp = Path("C:\\Users\\thesa\\AppData\\Local\\Temp\\soffice-10416-bQefydwUfs2F")
>>> tmp.as_uri()
'file:///C:/Users/thesa/AppData/Local/Temp/soffice-10416-bQefydwUfs2F'

PYTEST deleted EVERYTHING in my documents folder. Can I recover it?

I was following a tutorial in the pytest documentation for creating temporary directories, https://docs.pytest.org/en/stable/tmpdir.html and when I executed the following code, the contents of my entire documents folder was deleted.
import pytest
import os
#pytest.fixture()
def tmdirmak(tmpdir_factory):
f = tmpdir_factory.mktemp("data")
return f
def test_temp(tmp_path):
d = tmp_path / "sub1"
d.mkdir()
p = d / "tem.txt"
p.write_text("hello")
assert p.read_text() == "hello"
os.system("ls")
This file was saved in my documents folder and this is where I ran the command pytest --basetemp=. -s test_paths.py which accounting to the documentation is how you change where the temporary directory is made. I did not want the temporary directory to be made in /tmp but rather I wanted it created in the same directory that my code lives. When I ran this I got the following pytest output
test_paths.py E
================================================= ERRORS ==================================================
_______________________________________ ERROR at setup of test_temp _______________________________________
path = '/Users/matthewclark/Documents', ignore_errors = False
onerror = functools.partial(<function on_rm_rf_error at 0x7fe29a845dd0>, start_path=PosixPath('/Users/matthewclark/Documents'))
def rmtree(path, ignore_errors=False, onerror=None):
"""Recursively delete a directory tree.
If ignore_errors is set, errors are ignored; otherwise, if onerror
is set, it is called to handle the error with arguments (func,
path, exc_info) where func is platform and implementation dependent;
path is the argument to that function that caused it to fail; and
exc_info is a tuple returned by sys.exc_info(). If ignore_errors
is false and onerror is None, an exception is raised.
"""
if ignore_errors:
def onerror(*args):
pass
elif onerror is None:
def onerror(*args):
raise
if _use_fd_functions:
# While the unsafe rmtree works fine on bytes, the fd based does not.
if isinstance(path, bytes):
path = os.fsdecode(path)
# Note: To guard against symlink races, we use the standard
# lstat()/open()/fstat() trick.
try:
orig_st = os.lstat(path)
except Exception:
onerror(os.lstat, path, sys.exc_info())
return
try:
fd = os.open(path, os.O_RDONLY)
except Exception:
onerror(os.lstat, path, sys.exc_info())
return
try:
if os.path.samestat(orig_st, os.fstat(fd)):
_rmtree_safe_fd(fd, path, onerror)
try:
> os.rmdir(path)
E PermissionError: [Errno 13] Permission denied: '/Users/matthewclark/Documents'
../anaconda3/lib/python3.7/shutil.py:496: PermissionError
During handling of the above exception, another exception occurred:
path = '/Users/matthewclark/Documents', ignore_errors = False
onerror = functools.partial(<function on_rm_rf_error at 0x7fe29a845dd0>, start_path=PosixPath('/Users/matthewclark/Documents'))
def rmtree(path, ignore_errors=False, onerror=None):
"""Recursively delete a directory tree.
If ignore_errors is set, errors are ignored; otherwise, if onerror
is set, it is called to handle the error with arguments (func,
path, exc_info) where func is platform and implementation dependent;
path is the argument to that function that caused it to fail; and
exc_info is a tuple returned by sys.exc_info(). If ignore_errors
is false and onerror is None, an exception is raised.
"""
if ignore_errors:
def onerror(*args):
pass
elif onerror is None:
def onerror(*args):
raise
if _use_fd_functions:
# While the unsafe rmtree works fine on bytes, the fd based does not.
if isinstance(path, bytes):
path = os.fsdecode(path)
# Note: To guard against symlink races, we use the standard
# lstat()/open()/fstat() trick.
try:
orig_st = os.lstat(path)
except Exception:
onerror(os.lstat, path, sys.exc_info())
return
try:
fd = os.open(path, os.O_RDONLY)
except Exception:
onerror(os.lstat, path, sys.exc_info())
return
try:
if os.path.samestat(orig_st, os.fstat(fd)):
_rmtree_safe_fd(fd, path, onerror)
try:
os.rmdir(path)
except OSError:
> onerror(os.rmdir, path, sys.exc_info())
E PermissionError: [Errno 13] Permission denied: '/Users/matthewclark/Documents'
../anaconda3/lib/python3.7/shutil.py:498: PermissionError
============================================ 1 error in 0.21s =============================================
I think returned to find all my folders and documents in my documents directory to be deleted! I suspect since pytest normally thinks it is in /tmp it just clears out all the stuff in that folder when it is done, including the things it didn't create. If this is true, this is a horrible bug. What's strange is I received these permission errors yet my contents were deleted anyway.

cloud-init: Can write_files be merged?

Can write_files be merged? I can't seem to get the merge_how syntax correct. Only files in the last write_files are being created.
Thanks
The answer is yes.
When working with multi-part MIME, you must add the following to the header of each part.
Merge-Type: list(append)+dict(no_replace,recurse_list)+str()
Below is a modified version of the helper script provided in the cloud-init documentation.
#!/usr/bin/env python3
import click
import sys
import gzip as gz
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
#click.command()
#click.option('--gzip', is_flag=True,
help='gzip MIME message to current directory')
#click.argument('message', nargs=-1)
def main(message: str, gzip: bool) -> None:
"""This script creates a multi part MIME suitable for cloud-init
A MESSAGE has following format <filename>:<type> where <filename> is the
file that contains the data to add to the MIME message. <type> is the
MIME content-type.
MIME content-type may be on of the following:
text/cloud-boothook
text/cloud-config
text/cloud-config-archive
text/jinja2
text/part-handler
text/upstart-job
text/x-include-once-url
text/x-include-url
text/x-shellscript
EXAMPLE:
write-mime-multipart afile.cfg:cloud-config bfile.sh:x-shellscript
"""
combined_message = MIMEMultipart()
for message_part in message:
(filename, format_type) = message_part.split(':', 1)
with open(filename) as fh:
contents = fh.read()
sub_message = MIMEText(contents, format_type, sys.getdefaultencoding())
sub_message.add_header('Content-Disposition',
'attachment; filename="{}"'.format(filename))
sub_message.add_header('Merge-Type',
'list(append)+dict(no_replace,recurse_list)+str()')
combined_message.attach(sub_message)
if gzip:
with gz.open('combined-userdata.txt.gz', 'wb') as fd:
fd.write(bytes(combined_message))
else:
print(combined_message)
if __name__ == '__main__':
main()

How to convert a directory to a ZIP?

I wanted to know how to convert a file (x) directly to a ZIP (x.zip), and convert it back into a normal file, using python (3.7)
I use shutil
import shutil
#creating archive
shutil.make_archive(output_filename, 'zip', dir_name)
#unpacking archive
shutil.unpack_archive(input_filename, extract_dir, 'zip')
you can also do with zipfile
import os
import zipfile
#creating zip file
zf = zipfile.ZipFile("myzipfile.zip", "w")
for dirname, subdirs, files in os.walk("mydirectory"):
zf.write(dirname)
for filename in files:
zf.write(os.path.join(dirname, filename))
zf.close()
#extracting zip file
with zipfile.ZipFile("myzipfile.zip", 'r') as zip:
zip.extractall()
For zipping and Unzipping without password protected:
For zipping the File, You can use pyminizip module
import pyminizip
compression_level = 5 # 1-9
pyminizip.compress("/home/paulsteven/src.txt",'src', "dst.zip", None, compression_level)
For Unzipping the File, Use Zipfile module
from zipfile import ZipFile
with ZipFile('/home/paulsteven/dst.zip') as zf:
zf.extractall()
For zipping and Unzipping with password protected:
For ZIP:
import pyminizip
compression_level = 5 # 1-9
pyminizip.compress("/home/paulsteven/src.txt",'src', "dst.zip", "password", compression_level)
For UNZIP:
from zipfile import ZipFile
with ZipFile('/home/paulsteven/dst.zip') as zf:
zf.extractall(pwd=b'password')
To crack a ZIP file has been protected:
import threading
from zipfile import ZipFile
def ext(f, pw):
try:
f.extractall(pwd=pw)
print('Cracked the .zip file')
print('::::: %s' % pw)
except:
pass
f = 'file.zip'
pw = open('password.txt', 'r').readline()
for p in pw:
crack=threading.Thread(target=ext, args=[f, p])
crack.start()

environment variables using subprocess.check_output Python

I'm trying to do some basic module setups on my server using Python. Its a bit difficult as I have no access to the internet.
This is my code
import sys
import os
from subprocess import CalledProcessError, STDOUT, check_output
def run_in_path(command, dir_path, env_var=''):
env_var = os.environ["PATH"] = os.environ["PATH"] + env_var
print(env_var)
try:
p = check_output(command, cwd=dir_path, stderr=STDOUT)
except CalledProcessError as e:
sys.stderr.write(e.output.decode("utf-8"))
sys.stderr.flush()
return e.returncode
else:
return 0
def main():
requests_install = run_in_path('python setup.py build',
'D:\installed_software\python modules\kennethreitz-requests-e95e173')
SQL_install = run_in_path('python setup.py install', # install SQL module pypyodbc
'D:\installed_software\python modules\pypyodbc-1.3.3\pypyodbc-1.3.3')
setup_tools = run_in_path('python setup.py install', # install setup tools
'D:\installed_software\python modules\setuptools-17.1.1')
psycopg2 = run_in_path('easy_install psycopg2-2.6.1.win-amd64-py3.3-pg9.4.4-release', # install setup tools
'D:\installed_software\python modules', ';C:\srv_apps\Python33\Scripts\easy_install.exe')
print('setup complete')
if __name__ == "__main__":
sys.exit(main())
now it gets tricky when i start trying to use easy install. It appears my env variables are not being used by my subprocess.check_output call
File "C:\srv_apps\Python33\lib\subprocess.py", line 1110, in _execute_child
raise WindowsError(*e.args)
FileNotFoundError: [WinError 2] The system cannot find the file specified
I don't want to have to upgrade to 3.4 where easy install is installed by default because my other modules are not supported on 3.4. My main challenge is the subprocess.check_call method does not take environment variables as an input and im wary of trying to use Popen() as I have never really got it to work successfully in the past. Any help would be greatly appreciated.
PATH should contain directories e.g., r'C:\Python33\Scripts', not files such as: r'C:\Python33\Scripts\easy_install.exe'
Don't hardcode utf-8 for an arbitrary command, you could enable text mode using universal_newlines parameter (not tested):
#!/usr/bin/env python3
import locale
import sys
from subprocess import CalledProcessError, STDOUT, check_output
def run(command, *, cwd=None, env=None):
try:
ignored = check_output(command, cwd=cwd, env=env,
stderr=STDOUT,
universal_newlines=True)
except CalledProcessError as e:
sys.stderr.write(e.output)
sys.stderr.flush()
return e.returncode
else:
return 0
Example:
import os
path_var = os.pathsep.join(os.environ.get('PATH', os.defpath), some_dir)
env = dict(os.environ, PATH=path_var)
run("some_command", cwd=some_path, env=env)
run("another_command", cwd=another_path, env=env)