Compiling and Executing Java file in python - python

how can I open an java file in python?, i've search over the net and found this:
import os.path, subprocess
from subprocess import STDOUT, PIPE
def compile_java (java_file):
subprocess.check_call(['javac', java_file])
def execute_java (java_file):
cmd=['java', java_file]
proc=subprocess.Popen(cmd, stdout = PIPE, stderr = STDOUT)
input = subprocess.Popen(cmd, stdin = PIPE)
print(proc.stdout.read())
compile_java("CsMain.java")
execute_java("CsMain")
but then I got this error:
Traceback (most recent call last):
File "C:\Python33\lib\subprocess.py", line 1106, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\casestudy\opener.py", line 13, in <module>
compile_java("CsMain.java")
File "C:\casestudy\opener.py", line 5, in compile_java
subprocess.check_call(['javac', java_file])
File "C:\Python33\lib\subprocess.py", line 539, in check_call
retcode = call(*popenargs, **kwargs)
File "C:\Python33\lib\subprocess.py", line 520, in call
with Popen(*popenargs, **kwargs) as p:
File "C:\Python33\lib\subprocess.py", line 820, in __init__
restore_signals, start_new_session)
File "C:\Python33\lib\subprocess.py", line 1112, in _execute_child
raise WindowsError(*e.args)
FileNotFoundError: [WinError 2] The system cannot find the file specified
>>>
the python file and java file is in the same folder, and I am using Python 3.3.2, how can I resolve this? or do you guys have another way on doing this?, any answer is appreciated thanks!

I think it isn't recognizing the javac command. Try manually running the command and if javac isn't a recognized command, register it in your PATH variable and try again.
Or you could just try typing the full pathname to the Java directory for javac and java.

you need to add path to your java file name. like this:
compile_java("C:\\path\to\this\CsMain.java")

Related

subprocess.run([‘cmd’, ‘args’]) returns FileNotFoundError

While coding an os extension with the “subprocesses” package, the FileNotFoundError seems to be re-occuring.
My code:
perm = “filename1 filename2”
subprocess.run(‘ren’, perm)
This returns the error:
Traceback (most recent call last):
File "main.py", line 46, in <module>
listeningfunc()
File "main.py", line 37, in listeningfunc
mv(listening.split(' ', 1)[1])
File "main.py", line 16, in mv
subprocess.run(['ren', perm])#, cwd=(os.getcwd()), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/subprocess.py", line 493, in run
with Popen(*popenargs, **kwargs) as process:
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/subprocess.py", line 858, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/subprocess.py", line 1704, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'ren‘
I tried using
subprocess.run([’ren’, perm], cwd=(os.getcwd()), stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
which seemed to resolve the issue (removes the error) but the function does not run. Can anyone help me with this? I’ve noticed that the package os also has similar issues.
Using OS package does not result in an error, but results in:
sh: 1: ren: not found
That's because ren is a cmd built-in. Several options:
perm = “filename1 filename2”
subprocess.run(‘ren’, perm, shell=True)
or prepend with cmd /c
perm = “filename1 filename2”
subprocess.run(['cmd','/c',‘ren’, "filename1","filename2"])
or way better: use native os functions as it's not worth to call ren when you can call os.rename
os.rename("filename1","filename2")
another way with shutil
shutil.move('filename1','filename2')

using Python to send subprocess commands with escape characters

I'm using a python script which uses subprocess to pass a commmand to the terminal. Part of the command that I'm passing involves paths which contain parentheses. Python handles strings with parentheses fine, but of course terminal does not handle these without escape characters.
I'm trying to pass variables to a command line program by feeding a string into subprocess, but here's simple example to reproduce the error:
import subprocess
path = '/home/user/Desktop/directory(2018)'
command_str = 'rmdir ' + path
print (subprocess.run(command_str))
which gives me this error:
Traceback (most recent call last):
File "ex.py", line 7, in <module>
print (subprocess.run(command_str))
File "/usr/lib/python3.6/subprocess.py", line 403, in run
with Popen(*popenargs, **kwargs) as process:
File "/usr/lib/python3.6/subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.6/subprocess.py", line 1344, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'rmdir /home/user/Desktop/directory(2018)': 'rmdir /home/user/Desktop/directory(2018)'
When I write it directly into the terminal with escape characters it works great.
$ rmdir /home/user/Desktop/directory\(2018\)
But in Python when I try to add escape characters to the strings before calling subprocess:
command_str = command_str.replace('(','\(')
command_str = command_str.replace(')','\)')
I get the same error as before because, unlike print, the subprocess string adds a second escape character which gets passed to the terminal.
Traceback (most recent call last):
File "ex.py", line 7, in <module>
print (subprocess.run(command_str))
File "/usr/lib/python3.6/subprocess.py", line 403, in run
with Popen(*popenargs, **kwargs) as process:
File "/usr/lib/python3.6/subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.6/subprocess.py", line 1344, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'rmdir /home/user/Desktop/directory\\(2018\\)': 'rmdir /home/user/Desktop/directory\\(2018\\)'
Is there a way to fix this particular error? Either by doing something different with replace or subprocess.run? (I'm not looking for a better way to remove directories.) Thanks.
Python implements rm and rmdir so no need to call a process. In general, if you want to skip shell processing on a command in subprocess, don't use the shell.
import subprocess
path = '/home/user/Desktop/directory(2018)'
command = ['rmdir', path]
print (subprocess.run(command, shell=False))
The shell breaks a command line into a list of arguments. You can build that list yourself and skip the shell completely.
Do not use subprocess, and you don't have to worry about shell escaping. Use the high-level file operation APIs provided in stdlib's shutil:
import shutil
shutil.rmtree('/home/user/Desktop/directory(2018)')

Calling Popen in Python on a MAC - Error can not find file

When I try to shell out of my Python 3.51 program to run the Popen command I get the following errors. Yet when I copy the exact string I'm passing to Popen to the Terminal command line it works fine and opens the file in Adobe Reader which is my default app for the .pdf files.
Here is the Code:
finalCall = r'open /Users/gbarnabic/Documents/1111/combined.pdf'
print(finalCall)
pid_id = subprocess.Popen(finalCall).pid
Here is the error:
open /Users/gbarnabic/Documents/1111/combined.pdf
Exception in Tkinter callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/tkinter/init.py", line 1549, in call
return self.func(*args)
File "pdfcomb2.py", line 212, in change_dir
self.openPDF(outFileName, pageNum)
File "pdfcomb2.py", line 426, in openPDF
subprocess.run(finalCall)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 696, in run
with Popen(*popenargs, **kwargs) as process:
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 950, in init
restore_signals, start_new_session)
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/subprocess.py", line 1544, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'open /Users/gb/Documents/1111/combined.pdf'
Georges-MBP:filepicktest gb$ open /Users/gb/Documents/1111/combined.pdf
Georges-MBP:filepicktest gb$
With Popen you need to set shell=True to pass command as a string or split command in a list of arguments. Could be done with shlex
import shlex
import subprocess
subprocess.Popen(shlex.split('open ....'))
You could check example in documentation:
https://docs.python.org/2/library/subprocess.html#subprocess.Popen
So the error here means that Python try to run file with name open /Users/gb/Documents/1111/combined.pdf. Obviously it doesn't exist

Python Subprocess clarification

I am trying to execute a program with python using subprocess
The format our professor gave us was subprocess(path/executableProgram)
File: OS377.py
I am doing it as subprocess(['/home/Joseph/OS377.py']) but I am getting errors
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python3.2/subprocess.py", line 471, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python3.2/subprocess.py", line 745, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.2/subprocess.py", line 1361, in _execute_child
raise child_exception_type(errno_num, err_msg)
OSError: [Errno 8] Exec format error
I need to execute a file using this format but am unsure how to go about it
Code:
def RUN(file):
pid = os.fork() #pid is non-zero in the parent process and 0 in the child
if pid: #parent
os.waitpid(pid,0)
elif pid == 0: #child
print("path is : ")
child(file)
def child(file):
#path = os.path.abspath(file)
#print(path)
subprocess.call(os.path.abspath('OS377.py'))
subprocess.call(['python', os.path.abspath('OS377.py')].
The file you're calling, a python script, may not be marked as executable (chmod u+x file.py). Alternatively, you should probably be executing it with $ python file.py - which is calling the python interpreter and passing it the name of your script as the first argument. So you should put it as subprocess.call(['python', '/home/Joe/file.py'].
Btw, did you mean subprocess.call() instead of just subprocess()?

Python interface wifi.Cell.all(Interface) giving system error

I am trying to connect to the wireless network using wifi. As per the documents I have written the code, but it gives system error that file not found. As I can see the argument description of the Cell.all() is interface but we are providing literal as argument. What might be the problem?
import time
import datetime
from wifi import Cell, Scheme
while True :
print datetime.datetime.now()
print Cell.all('wlan0')
time.sleep(5)
>>>
2015-01-25 12:38:43.784000
Traceback (most recent call last):
File "D:\Documents\Development\Script\AutoLogon.py", line 9, in <module>
print Cell.all('wlan0')
File "C:\Python27\lib\site-packages\wifi\scan.py", line 29, in all
stderr=subprocess.STDOUT)
File "C:\Python27\lib\subprocess.py", line 537, in check_output
process = Popen(stdout=PIPE, *popenargs, **kwargs)
File "C:\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 896, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
>>>
The python interface wifi was developed for Linux. I may be able to use the library using cygwin.

Categories