I would use subprocess this way:
import subprocess
subprocess.call(['java', '-jar', 'Blender.jar'])
But, if you have a properly configured /proc/sys/fs/binfmt_misc/jar you should be able to run the jar directly, as you wrote.
So, which is exactly the error you are getting? Please post somewhere all the output you are getting from the failed execution.
Answer from redShadow on Stack OverflowI would use subprocess this way:
import subprocess
subprocess.call(['java', '-jar', 'Blender.jar'])
But, if you have a properly configured /proc/sys/fs/binfmt_misc/jar you should be able to run the jar directly, as you wrote.
So, which is exactly the error you are getting? Please post somewhere all the output you are getting from the failed execution.
This always works for me:
from subprocess import *
def jarWrapper(*args):
process = Popen(['java', '-jar']+list(args), stdout=PIPE, stderr=PIPE)
ret = []
while process.poll() is None:
line = process.stdout.readline()
if line != '' and line.endswith('\n'):
ret.append(line[:-1])
stdout, stderr = process.communicate()
ret += stdout.split('\n')
if stderr != '':
ret += stderr.split('\n')
ret.remove('')
return ret
args = ['myJarFile.jar', 'arg1', 'arg2', 'argN'] # Any number of args to be passed to the jar file
result = jarWrapper(*args)
print result
Do you want to execute code from .jar, or open it?
If open, then .jar file is the same format as .zip files and you can use zipfile module to manipulate it. Example:
def show_jar_classes(jar_file):
"""prints out .class files from jar_file"""
zf = zipfile.ZipFile(jar_file, 'r')
try:
lst = zf.infolist()
for zi in lst:
fn = zi.filename
if fn.endswith('.class'):
print(fn)
finally:
zf.close()
If you want to execute it then I prefer creating simple batch/shell script which execute java with some parameters like -Xmx and with environment settings required by application.
For the previous question, Executing it is easy.
import os
os.system('start X:\file.jar')
This is what I am using right now
os.system("java -jar FULL_PATH\RR.jar")
A command prompt console window pops up for an instance and all i can read is 4 lines reading success followed by some other text.
Any help will be welcome
Hi, I've got a .jar file that outputs a lot of text continuously. I've been using the following code to open the .jar in python.
import subprocess subprocess.call(['java', '-jar', 'prox.jar'])
I can see that all is working because I can see the output text in the IDLE, but I'm stuck on how to execute code based on the continuous output. So like...
if "test" in live_output_of_Jar: ... if "othertext" in... you get the idea.
Thanks!
I want to build a script that will open jar files of Minecraft mods and extract information like the version and name of the mod from files inside them. The problem is that I can't seem to open text files and use them, or list the content of only certain folders from inside the jar file without having to extract it first.
I've installed the zipfile plugin, but have only been able to open the jar file itself. When I try to open a folder inside the jar file and list its contents I get an error "listdir: path should be string, bytes, os.PathLike or None, not ZipExtFile". Here's the code:
import os
from zipfile import *
mods_path = "D:\Coding\Python\Projekte\Minecraft Updater\mods"
os.chdir(mods_path)
test_mod = "Quark-r2.4-271.jar"
with ZipFile(test_mod, "r") as z:
with z.open("META-INF/") as folder:
os.listdir(folder)
It seems the listdir functions only works in normal folders. I haven't been able to find any documentation on methods for the ZipExtFile class to achieve what I'm trying to do. My concern is that the continuous extraction and deletion of files would impact the performance of my program, which I'm trying to keep as minimal as possible. Thanks in advance!
get_path_lists uses recursion as so:
for d in dirs:
get_path_list(d)
Namely, for every directory you do a full traversal of the whole tree: walk is already recursive! Or you would, if you actually passed in a full path os.path.join(root, d). You don't even use the result, so remove it.
Your
for f in files:
if f.endswith(".jar"):
app_list.append(root)
break
can be simplified to
if any(f.endswith(".jar") for f in files):
app_list.append(root)
I would convert get_path_list to an iterator:
def get_path_list(base_path):
for root, dirs, files in os.walk(base_path):
if any(f.endswith(".jar") for f in files):
yield root
Success!
I would also consider a move to pathlib for its extended globbing:
def get_path_list(base_path):
return set(path.parent for path in Path(base_path).glob("**/*.jar"))
although this comes with its own disadvantages.
get_app_name can be prettier more platform independent with pathlib.PurePath:
def get_app_name(lib_path):
path = PurePath(lib_path)
path = path.relative_to(path.anchor)
return "-".join(path.parts)
The .relative_to stuff removes any drive or root, and then you can just join the parts.
In create_command you check if len(app_list) > 0; it's more idiomatic to just check if app_list.
You implicitly return None when empty; it seems to me you should be throwing an error. You should also use early exit to keep things cleaner.
Your formatting strings don't need numbers:
command = "{}{} Core -a {} -o {}".format(full_path, get_extension(), app_name, output_file)
for app_path in app_list:
command += " -s {}".format(app_path)
Your for loop is non-idiomatic; you should never use += on immutable objects in a list without good reason. Here, just use:
command = "{}{} Core -a {} -o {}".format(full_path, get_extension(), app_name, output_file)
command += "".join(" -s {}".format(app_path) for app_path in app_list)
Even so, the real problem is that dependency_check uses shell=True; it shouldn't. Pass in a list instead:
command = [full_path + get_extension(), "Core", "-a", app_name, "-o", output_file]
for app_path in app_list:
command.append("-s")
command.append(app_path)
return command
The old method broke when any of the inputs had, say, spaces or asterisks in.
Ideally you should not have if conditions in your tests. You should always know exactly what it is that you want to test.
test_app_namehas a check on the platform. You should be able to mock it out and test the functionality under a 'windows' and a 'non-windows' environment. I'd split it out into different tests.remove_old_fileswalks through a dir on your machine. Mock it out or include it in the repo for your code. Ideally mock it out if you don't really care about particulars of the files.You have a lot of hardcoded paths in your code. This will not work on any other machine. You'll need some way of fixing this.
On a larger note:
You have the correct picture of a unit test, but you seem to try adn cover all cases under a single test. You need to test out all the methods, but you can split it out into multiple tests:
eg:
Let's pick get_extension. There are 2 code paths in that method. So lets write 2 methods for it.
1. test_get_extension_windows
2. test_get_extension_non_windows
That should cover all cases for that method and we know exactly what gets executed in there. No need for conditions in our code. You can go on the same path for the other tests too.