Import variable from Python script to Batch file - python

I have a python script containing vraibles
example.py
"src = komponent/cool,
komponent/raw" /* path of source files */
and i have a batch file which needs to import the value of "src" for postporcessing
example.bat
--cs-include ='komponent/cool'* --cs-include ='komponent/raw'*
Is there any way to import directly between files (without using any other conversion) ?
"PyBat.bat" is one option but i am trying to figure out a better choice dont want to add on one more tool (not specifically)...as my project itself has too different files and interacting source.
Any help is appreciated..
Thank you in advance..!!!

In Python
Create a temp batch file in %TEMP%\setvars.bat containing SET commands to set environment vars.
You could use subprocess.POpen to run an ECHO something > path batch command so that %TEMP% can be used.
In Batch
Call the temp batch file : the vars are now available to use.

Solution is...
1.set a argument in the python itself.
2.call the batch file from python script and along with pass the argument using
os.system(cmd) and cmd as a string.
It will set the path itself.

Related

PYTHON AND BATCH SCRIPT: Run file if it exists and create if it doesn't

Full Disclaimer: I DO NOT KNOW PYTHON.
Hi Guys,
I have made an AutoHotKey Script for my volume keys. I would like to create a batch file which runs a python file (so if I change computers, I can easily create this scripts) which would do the following
Check if volume_keys.ahk exists in the D Drive
If it exists, run that;
If it doesn't exist, then create a file named volume_keys.ahk and add my script to it.
My script is:
^!NumpadMult::Send {Volume_Mute}
^!NumpadAdd::Send {Volume_Up}
^!NumpadSub::Send {Volume_Down}
I know how to code the .bat file and just need help for the python point-of-view, but I request the community to check it:
#ECHO OFF
ECHO This script will run an AHK Script. If you want to stop this process from happening, then cross this window off.If you want to continye:
pause
cd d:
D:\run_volume_keys_ahk_script.py
I really appreciate any help by the community.
Thanks in advance
You can use the os library for this. Here's what the python program would look like.
import os
if os.path.isfile('D:\\volume_keys.ahk'): # check if it exists
os.system('D:\\volume_keys.ahk') # execute it
else:
with open('D:\\volume_keys.ahk', 'w') as f: # open it in w (write) mode
f.write('^!NumpadMult::Send {Volume_Mute} \
^!NumpadAdd::Send {Volume_Up} \
^!NumpadSub::Send {Volume_Down}') # Write to file
os.system('D:\\volume_keys.ahk') # execute
To activate the ahk script, you might want to use the subprocess module, of which I took the example from here
import subprocess
subprocess.call(["path/to/ahk.exe", "script.ahk"])
Note that you'll have to find the ahk executable on a computer before you can use the script, maybe you want to automatically check that too.
You can set the path you want to check for scripts in one string, and then add the filenames of your scripts as strings to a list. You can use listdir() from the os module to see any files and directories at a given path, then iterate over your scriptnames and check if it exists in that list of files. If it does, run it.
In this example I copy-pasted your script into a string as value for the key 'scriptname' in a dictionary, so that python can actually create the script file. This isn't really a neat way to do it though, you might want to have your scripts prepared in a directory next to your python script and copy them from there. See an example of how here
from os import listdir
from os.path import isfile, join
CHECK_PATH = "D:"
AHK_EXECUTABLE_PATH = "path/to/ahk.exe"
SCRIPTS_TO_CHECK = {'script1.ahk':"""^!NumpadMult::Send {Volume_Mute}
^!NumpadAdd::Send {Volume_Up}
^!NumpadSub::Send {Volume_Down} """, 'script2.ahk':" some other script here"}
files_to_check = set(listdir(CHECK_PATH)) # using a set for fast lookup later
for scriptname, script in SCRIPTS_TO_CHECK.items():
if not scriptname in files_to_check:
print(f"script {scriptname} not found, creating it.")
with open(scriptname, 'w') as file:
file.write(script)
# else
subprocess.call(AHK_EXECUTABLE_PATH, scriptname)

how to modify txt file properties with python

I am trying to make a python program that creates and writes in a txt file.
the program works, but I want it to cross the "hidden" thing in the txt file's properties, so that the txt can't be seen without using the python program I made. I have no clues how to do that, please understand I am a beginner in python.
I'm not 100% sure but I don't think you can do this in Python. I'd suggest finding a simple Visual Basic script and running it from your Python file.
Assuming you mean the file-properties, where you can set a file as "hidden". Like in Windows as seen in screenshot below:
Use operating-system's command-line from Python
For example in Windows command-line attrib +h Secret_File.txt to hide a file in CMD.
import subprocess
subprocess.run(["attrib", "+h", "Secret_File.txt"])
See also:
How to execute a program or call a system command?
Directly call OS functions (Windows)
import ctypes
path = "my_hidden_file.txt"
ctypes.windll.kernel32.SetFileAttributesW(path, 2)
See also:
Hide Folders/ File with Python
Rename the file (Linux)
import os
filename = "my_hidden_file.txt"
os.rename(filename, '.'+filename) # the prefix dot means hidden in Linux
See also:
How to rename a file using Python

Open .bat file with Python - not working

I have 3 different files, one Python file and two .bat files. They communicate between each other (hopefully).
When I execute the "Process_Videos.bat" by itself (double clicking in the windows explorer) it works fine, but whenever I call it from the Python file it doesnt work at all, just says "press any button to continue..."
I really need to have this structure, calling the "Process_Videos.bat" from a Python file, since I am extracting some web info. The "pythonExecute.bat" just works as a trigger for the entire process.
Also I have tried the "subprocess" approach, but not working either.
The files and respective code:
pythonExecute.bat
python "D:\\tests\\pythonCall.py"
pythonCall.py
import os
os.system('D:\\tests\\3.asc\\Process_Videos_asc.bat')
Process_Videos.bat
#echo off
setlocal EnableDelayedExpansion
set "FolderBaseName=TestName"
set "DropBoxFolder=D:\tests\3.asc\myDropBoxFolder"
set "BaseOutputFolder=D:\tests\3.asc\TEMP"
for %%I in (*.png) do (
set "slaveName=%%~nI"
set "slaveName=!slaveName:~6!
set "OutputFolder=%BaseOutputFolder%_!slaveName!"
echo !slaveName!
md "!OutputFolder!" 2>nul
for %%J in (*.mp4*) do (
ffmpeg -i "%%~fJ" -i "%%~fI" -filter_complex overlay "!OutputFolder!\%%~nJ.mp4"
)
"C:\Program Files\WinRAR\rar.exe" a -cfg- -ep1 -inul -m5 "%DropBoxFolder%\%FolderBaseName%_!slaveName!" "!slaveName:~6!\*"
rd /S /Q "!OutputFolder!"
)
pause
You need to:
a) Invoke your batch file within the directory it is in, (e.g. by changing directory first), and
b) Get rid of the pause at the end of the batch file.
You should also consider replacing the batch file altogether - python can do all of the things that it does much more neatly.
The accepted answer to this SO question gives some very good tips.

Applying a perl script to every file in a directory and obtain output using Python

I am trying to make a python script that will open a directory, apply a perl script to every file in that directory and get its out put in either multiple text files or just one.
I currently have:
import shlex, subprocess
arg_str = "perl tilt.pl *.pdb > final.txt"
arg = shlex.split(arg_str)
import os
framespdb = os.listdir("prac_frames")
for frames in framespdb:
subprocess.Popen(arg, stdout=True)
I keep getting *.pdb not found. I am very new to all of this so any help trying to complete this script would help.
*.pdb not found means exactly that - there won't be a *.pdb in whatever directory you're running the script... and as I read the code - I don't see anything to imply it's within 'frames' when it runs the perl script.
you probably need os.chdir(path) before the Popen.
How do I "cd" in Python?
...using a python script to run somewhat dubious syscalls to perl may offend some people but everyone's done it.. aside from that I'd point out:
always specify full paths (this becomes a problem if you will later say, want to run your job automatically from cron or an environment that doesn't have your PATH).
i.e. 'which perl' - put that full path in.
./.pdb would be better but not as good as the fullpath/.pdb (which you could use instead of the os.chdir option).
subprocess.Popen(arg, stdout=True)
does not expand filename wildcards. To handle your *.pdb, use shell=True.

Python: system command

I spend a few hours writing a little script.
Basically what it does is create a new text file and fills it up with whatever.
I zip the text file --using zipfile-- and here's where my problem lies.
I want to run the Windows system command:
copy /b "imgFile.jpg" + "zipFile.zip" newImage.jpg
To merge the image "imgFile.jpg" and the zip "zipFile.zip".
So:
os.system("copy /b \"imgFile.jpg\" + \"zipFile.zip\" newImage.jpg")
When I run my script, it all seems to go fine.
But when it's done and I try to extract the 'newImage.jpg' file, it gives me:
The archive is either in unknown format or damaged
This ONLY happens when I run the system command within the script.
It works fine when I use the shell. It even works if I use a separate script.
I've double checked my zip file. Everything is in good shape.
Is there something I'm doing wrong? Something I'm not seeing?
Have you tried using shutil?
import shutil
shutil.copy(src, dst)
There may be a problem with the way Python is passing the arguments to the shell command. Try using subprocess.call. This method takes arguments as an array and passes them that way to the command:
import subprocess
subprocess.call(["copy", "/b", '"imgFile.jpg" + "zipFile.zip"', "newImage.jpg"])

Categories