Execute stand alone python script inside another script - python-3.x

I have made a .py file (i call it acomp.py) that reads from and SQL database and after a series of calculations and exports its output to an excel file.Later I sends this .xlsx file by e-mail to various persons.
I wish to put it inside another python script so I can use the schedule module to call acomp.py aromatically at selected times, run it and send the output by email:
def exec_scrpit():
exec(open("acomp.py", encoding='utf-8').read())
send_email()
schedule.every().day.at("07:20").do(exec_scrpit)
When the second script calls the fist it messes with the acom.py internal functions returning the error:
" File "<string>", line 125, in <lambda>
NameError: name 'modalidade_contrato' is not defined"
This 'modalidade_contrato' is defined inside acomp.py and it runs perfectly when I execute acom.py directly.
Any ideia how should I proceed? I think my whole strategy is not usual, but I have to do it this way because I do not have admin privileges on my computer.

I learned that you can simply run it as you would in cmd:
os.system(r'"C:\Users\user.name\Miniconda3\python.exe acomp.py"')

Related

Open .exe file using python and trying to pass parameter in the same python script

I'm trying to open a .exe file from Python and give it some instructions. Because I have thousands of models to run I need to automatize the process.
Here on Stackoverflow, I found several options that I tried. I am able to open .exe file but not able to fill the information in that and run the .exe. the place is always empty. I'm writing one of these solutions. [I'm using Python3]:
import os
your_bat_file_address = r'"C:\D_drive\testing\SAR\1100_star3\exmple.bat"' # example
os.startfile(your_bat_file_address)
in the exmple.bat file
"C:/D_drive/tool/EXMPLE.exe" --input1 "C:/D_drive/file/1st_file" --input2 "C:/D_drive/file/2st_file" --input3 "C:/D_drive/file/3st_file"

Sending Information from one Python file to another

I would like to know how to perform the below mentioned task
I want to upload a CSV file to a python script 1, then send file's path to another python script in file same folder which will perform the task and send the results to python script 1.
A working code will be very helpful or any suggestion is also helpful.
You can import the script editing the CSV to the python file and then do some sort of loop that edits the CSV file with your script 1 then does whatever else you want to do with script 2.
This is an advantage of OOP, makes these sorts of tasks very easy as you have functions set in a module python file and can create a main python file and run a bunch of functions editing CSV files this way.

I need to copy files from appdata/local to C drive and overwrite them each time the program is run

I use a program which, sadly corrupts some saved files at random times. To be helpful (although I am a novice at this) I am trying to make a Python program to basically backup those file from the AppData/local directory and put them in a folder on C. I need this program to overwrite the previously copied files each time it is run.
I need to generalize the AppData/local because each person who uses this program would, in theory, have a different user directory preceding the AppData folder.
I've tried running some of my own attempts at a solution.
I will post the results.
# Imports
import shutil
import os
import distutils
from distutils import dir_util
# Paths
# os.makedirs("C:/RevSaves-Backup")
path = '%LOCALAPPDATA%/Remnant'
backup_path = "C:/RevSaves-Backup"
# Procedures
print("The Very Basic Remnant Save Backup Utility")
print(" ")
print("Backing up the save source:")
print(path)
print(" ")
print("It is recommended you run this at regular intervals \nto ensure you have the latest saves up to date.")
distutils.dir_util.copy_tree(path, backup_path)
print("Backup completed.")
When I execute this via command prompt or PowerShell, I get the following message:
Traceback (most recent call last):
File "RevSaveBkUp.py", line 28, in
distutils.dir_util.copy_tree(path, backup_path)
File "C:\Users\candr\AppData\Local\Programs\Python\Python37-32\lib\distutils\dir_util.py", line 124, in copy_tree
"cannot copy tree '%s': not a directory" % src)
distutils.errors.DistutilsFileError: cannot copy tree '%LOCALAPPDATA%/Remnant': not a directory
I am having trouble "targeting" the system-specific local AppData folder.
After a lot of reading, I made the following solution if anyone else is trying to do something similar. I do not know if this is the "best" or "right" way of doing things, however.
Here is how I targeted the AppData Local folder regardless of the user logged in:
path = os.path.join(os.path.expanduser('~'), 'AppData', 'Local')
Some explanations for anyone who is new like me:
os.path.join basically connects folders together in the path. For example, using the above code, join would "connect" AppData to Local and the "User Folder" (referenced in the code as '~'). The output would look like this: C:\Users\your_username\AppData\Local
os.path.expanduser defines the user in question. For example, "~" targets the current user logged in. It goes inside the () because this is how you tell "your code" who, to target. If you wanted a specific user (if you had more than one) you could possibly use os.path.expanduser('Jane') I believe.
Keeping the notes above in reference, this method allowed me to define the variables I needed to and use them for the copy above, where I could not normally use the AppData directory as I wanted.
This was done by using the following code as an example:
path = os.path.join(os.path.expanduser('~'), 'AppData', 'Local')
backup_path = "C:/MyBackupFolder"
Finally we executed the copy with this:
distutils.dir_util.copy_tree(path, backup_path)
The above copied The AppData information I needed to the backup folder.
I hope this helps everyone learn as I did, it came in quite handy.

How to add a new method to an existing import in python? Specifically moviepy

For whatever reason, Python is not allowing me to access a custom method I created in moviepy's preview.py file. I just want to know how to correctly implement it into the file. For reference, before I changed the name of the method, it was working correctly.
I checked at least two __init.py__ files and they were effectively empty. I couldn't find if methods are initialized anywhere, and is probably what I'm missing.
I also tried restarting Git Bash and that didn't work either (another solution I saw).
Original:
#convert_masks_to_RGB
def preview(clip, fps=15, audio=True, audio_fps=22050, audio_buffersize=3000,
audio_nbytes=2, fullscreen=False):
Changed:
#requires_duration
#convert_masks_to_RGB
def preview_custom(clip, marker_overlay="marker_overlay.png", fps=15, audio=True, audio_fps=22050, audio_buffersize=3000,
audio_nbytes=2, fullscreen=False):
There are more than a few differences between the changed and original method, however at the moment the only result I expect is having the method be called correctly. Error is below:
Traceback (most recent call last):
File "T3AJM.py", line 249, in <module>
main()
File "T3AJM.py", line 34, in main
GUI_main_menu()
File "T3AJM.py", line 85, in GUI_main_menu
GUI_play_markers()
File "T3AJM.py", line 125, in GUI_play_markers
video.preview_custom(marker_overlay=TEMP_OVERLAY_FILE)
AttributeError: 'VideoFileClip' object has no attribute 'preview_custom'
Thank you for your time.
I'm not even sure if this technically fixes the problem, but just doing:
from moviepy.video.io.preview import *
and
preview_custom(video, marker_overlay=TEMP_OVERLAY_FILE)
fixed the problem. I have no idea why I had to change the way it was called, as doing clip.preview(), or in this case video.preview() worked perfectly fine before, but whatever.

Python3x - Write a python script to run other python scripts?

I have a number of python scripts that I would like to automate using Python's Datetime and Schedule module.
They are too numerous to consider breaking apart and adding to one large file.
What is the easiest way to write a python script that will open and run these other python scripts?
I have browsed similar questions but none offered a concrete answer that I could find. Thanks for your help.
A minimally demonstrative example
In a file called "child.py", write a file to the current directory:
with open('test', 'w') as f:
f.write('hello world')
Then, in a file called "parent.py", execute the "child.py" script:
import subprocess
subprocess.call(['python', 'child.py'])
Now, from your command line, you can type (assuming both "parent.py" and "child.py" are in the current directory):
python parent.py
In the next instant, you should see a file called "test" in your current directory. Open it up. What do you see?
Well, hello world of course!
The above example makes a child of the current process (meaning it inherits the environment variables in the parent), and waits until the child process completes before returning control to the parent. If you want the child script to run in the background, then you need to use Popen:
subprocess.Popen(['python', 'child.py'])

Resources