executing a python script within another python script - python

I wanted to run this script that saves images generated by a TDW script but the TDW script is definitely not running.
import glob
import os
import cv2
import subprocess
i = 0
frameSize = (512, 512)
path = 'CRIPP/annotations/icqa_dataset/IID/json'
for i in range(0, 1):
new_path = path + f'/example_{i}.json'
cmd = "recreate.py -json={new_path}"
os.system(cmd)
#subprocess.call(['recreate.py', '-json='+new_path])

I think you forgot to run script using python.
Change cmd line to cmd = "python recreate.py -json={new_path}"

Related

Python script violates the command-line character limit

I am using a Python script to batch convert many images in different folders into single pdfs (with https://pypi.org/project/img2pdf/):
import os
import subprocess
import img2pdf
from shutil import copyfile
def main():
folders = [name for name in os.listdir(".") if os.path.isdir(name)]
for f in folders:
files = [f for f in os.listdir(f)]
p = ""
for ffile in files:
p += f+'\\' + ffile + " "
os.system("py -m img2pdf *.pn* " + p + " --output " + f + "\combined.pdf")
if __name__ == '__main__':
main()
However, despite running the command via Powershell on Windows 10, and despite using very short filenames, when the number of images is very high (eg over 600 or so), Powershell gives me the error "The command line is too long" and it does not create the pdf. I know there is a command-line string limitation (https://learn.microsoft.com/en-us/troubleshoot/windows-client/shell-experience/command-line-string-limitation), but I also know that for powershell this limit is higher (Powershell to avoid cmd 8191 character limit), and I can't figure out how to fix the script. I would like to ask you if you could help me fix the script to avoid violating the character limit. Thank you
PS: I use the script after inserting it in the parent folder that contains the folders with the images; then in each subfolder the output pdf file is created.
Using img2pdf library you can use this script:
import img2pdf
import os
for r, _, f in os.walk("."):
imgs = []
for fname in f:
if fname.endswith(".jpg") or fname.endswith(".png"):
imgs.append(os.path.join(r, fname))
if len(imgs) > 0:
with open(r+"\output.pdf","wb") as f:
f.write(img2pdf.convert(imgs))

Unable to use subprocess in my colab python code

as part of a project I am doing wity Yolov4, I am trying to test multiple images with learned weights and copy the resulting images with added bounding boxes to my google drive.
The following is the code I am running on colab.
It just isn't working, and there is no log messages to debug. Please not if I run the command in the cmd variable directly, it is working fine, but that's just for one image.
My aim is to automate or "batch" the testing process.
Thanks for your help.
#%%capture
import os,sys
import subprocess
directory = '/content/darknet/data/testimages/'
for filename in os.listdir(directory):
#cmd = "./darknet detector test data/obj.data cfg/yolov4-obj.cfg /content/darknet/cfg/yolov4-obj_4000.weights /content/darknet/data/testimages/" + filename
cmd = "!./darknet detector test data/obj.data cfg/yolov4-obj.cfg /content/darknet/cfg/yolov4-obj_4000.weights /content/darknet/data/testimages/" + filename
try:
subprocess.run([sys.executable,cmd])
except:
print("failed")
#print(os.path.join(directory, filename))
cmd = "!cp 'predictions.jpg' '/mydrive/birds/results/" + filename + "_results.jpg' "
#print(cmd)
#cmd = "ls -ltr"
subprocess.run([sys.executable,cmd])
After a few hours of trial and error, a simple documentation search on Colab's page gave me the answer. It was under the heading "passing values to and from the shell". The following modified code does the trick for me.
%%capture
import os,sys
import subprocess
directory = '/content/darknet/data/testimages/'
for filename in os.listdir(directory):
cmd = "./darknet detector test data/obj.data cfg/yolov4-obj.cfg /content/darknet/cfg/yolov4-obj_4000.weights /content/darknet/data/testimages/" + filename
try:
!{cmd}
except:
print("failed")
cmd = "cp 'predictions.jpg' '/mydrive/birds/results/" + filename + "_results.jpg' "
!{cmd}
Try running your subprocess this way!
import os
import subprocess
env = os.environ.copy()
subprocess.run(cmd, shell=True, env=env)
This works for me. I find that this works for all OS. Do not add ! inside cmd.

Use shell:Programs in python

In windows you can use windows + r and type shell:Programs. Im trying to use this in my python script.
I have tryed doing this.
import os
path = os.getenv('shell:Programs')
and
from os import path
path = os.path.expandvars('shell:Programs')
This sadly only works for tags like %appdata%
Help!
Try this:
import os
os.startfile('shell:Programs')
OR
import subprocess
subprocess.call("explorer")
#with file path
#subprocess.call("explorer C:\\")

'FileNotFoundError' When Running R From Python

I am trying to run some R from python but I keep running into:
'FileNotFoundError: [WinError 2] The system cannot find the file specified'
I have tried searching for this problem but none of the solutions have worked.
The files are in the same directory and I'm running windows.
Here is my attempt the python:
import subprocess
import sys
from os import path
myfile = path.abspath(path.join(path.dirname(__file__), "test.R")
cmd = ['Rscript', myfile]
result = subprocess.check_output(cmd, universal_newlines=True)
print(result)
sys.stdout.flush()
The R code is just a simple Hello World.
Hope that you have added Rscript to path variable. Use below code to change your working directory as current directory
import subprocess
import sys
from os import path
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), "."))
os.chdir(os.path.abspath(os.path.dirname(__file__)))
myfile = path.abspath(path.join(path.dirname(__file__), "test.R")
cmd = ['Rscript', myfile]
result = subprocess.check_output(cmd, universal_newlines=True)
print(result)
sys.stdout.flush()

python code from batch file failures

When I run this code normally, it executes normally, but when I point my batch file at it (which I've tested on other code to make sure I know how to do it properly) it chooses not to make any of the dirs and the icon. Code is:
from sys import argv
import os, winshell
from win32com.client import Dispatch
script = argv
name = str(script[0])
cmd = 'start payload.txt'
os.system(cmd)
if not os.path.exists('C:\pythonspawn\clone'):
os.mkdir('C:\pythonspawn\clone')
os.system(r"copy payload.txt C:\pythonspawn\clone")
os.system(r"copy " + name + " C:\pythonspawn\clone")
desktop = winshell.desktop()
path = os.path.join("C:\pythonspawn\\", "Internet Explorer.lnk")
target = r"C:\pythonspawn\clone\file.py"
wDir = r"C:\pythonspawn\clone"
icon = r"C:\Program Files (x86)\Internet Explorer\iexplore.exe"
shell = Dispatch('Wscript.Shell')
shortcut = shell.CreateShortCut(path)
shortcut.Targetpath = target
shortcut.WorkingDirectory = wDir
shortcut.IconLocation = icon
shortcut.save()
and this is the batch file:
file.py %*

Categories