I call my python script with java and also pass variables. My The script alone in a PyCharm project works so far, only if I call it via Java (InteliJ) nothing happens.
The program should pass values to my script via Java so that the script changes and saves values in a Word Document (docx).
If I use the version of my script in the Intelij folder, it has problems importing docx.
I think the problem is that in the PyCharm project the docx data is directly in the project. This is not the case with Intelij and it should access the system data from docx.
I have already completely reinstalled lxml and docx but to no avail.
How do I have to change my program structure or my script so that it works.
Java:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class runPython {
public static void main(String[] args) throws IOException {
try {
ProcessBuilder builder = new ProcessBuilder("python", "C://Users//Notebook//IdeaProjects//bhTool_bridge//scripts//main.py", "Annemarie Brekow");
Process process = builder.start();
}
catch (Exception e){
e.printStackTrace();
}
}
}
Python:
from docx import Document
import sys
import os
document = Document('C:/Users/Notebook/IdeaProjects/bhTool_bridge/template/Muster_Rechnung.docx')
workingdirectory=os.getcwd()
def find_replace(paragraph_keyword, draft_keyword, paragraph):
if paragraph_keyword in paragraph.text:
# print("found")
paragraph.text = paragraph.text.replace(paragraph_keyword, draft_keyword)
for paragraph in document.paragraphs:
find_replace("$Kunden-Name", "Annemarie Brekow", paragraph)
print(paragraph.text)
document.save("C:/Users/Notebook/IdeaProjects/bhTool_bridge/template/Muster_Rechnung.docx")
EDIT:
Errormsg
Traceback (most recent call last):
File "C:\Users\Notebook\IdeaProjects\bhTool_bridge\scripts\main.py", line 2, in
from docx import Document
ModuleNotFoundError: No module named 'docx'
Related
Similar question have been asked here an year ago but no answer yet.
Im running a Python script via Java and I'm getting
ImportError: No module named numpy in <script> at line number 1
This is my code:
public void runScript(String filePath) throws Exception {
StringWriter writer = new StringWriter();
ScriptContext context = new SimpleScriptContext();
context.setWriter(writer);
Options.importSite = false;
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("python");
engine.eval(new FileReader(filePath), context);
System.out.println(writer);
}
How do I run script with it's imports?
Of course all the required installations have been installed (with pip install) and that the code runs perfectly when I run it not through java.
I am developing a quiz application in node.js. I need some python script to keep log of user,so I want to use key logger to keep monitoring the user while attempting the quiz.
Here is the python keylogger script:
from pynput.keyboard import Key, Listener
import logging
log_directory = r"G:/Pythonin Node/Keylogger/key_logger/public/log_files/"
logging.basicConfig(filename = (log_directory+"keylog.txt"), level = logging.DEBUG)
def on_press(key):
logging.info(str(key))
with Listener(on_press = on_press) as listener:
listener.join()
Script working well when i run it in pycharm.but when I call it from node application using python-shell I found an error:
{
traceback: "Traceback (most recent call last): File "script.py", line 1, in <module> from pynput.keyboard import Key, Listener ModuleNotFoundError: No module named 'pynput' ",
executable: "py",
options: null,
script: "script.py",
args: [
"xyz",
"abc"
],
exitCode: 1
}
This is the simple json response.
Here is my node code:
app.get('/', callD_alembert);
function callD_alembert(req, res) {
var x="xyz";
var y="abc";
var options = {
args:
[
x,
y
]
}
PythonShell.run('./script.py', options, function (err, data) {
if (err) res.send(err);
res.send(data.toString())
});
}
python shell executes the simple python script in which I don't use any external package.but when I to use "pynput" package and want to import it.it gives the following error:
Here is also running a python interpreter:
please help me to solve this issue.
Thank you
It looks like you are running the python interpreter in different environments.
Try adding the code below to your python script, and run it from pycharm and using PythonShell:
import sys
print(sys.executable)
If the printed paths are different, try modifying the options you pass to PythonShell, so that the path matches the one you have while running the script via pycharm:
var options = {
// replace this with the path you got by running the script in pycharm
pythonPath: 'path/to/python',
args:
[
x,
y
]
}
I have a simple GUI with two buttons and a rich text box. Button One uses the OpenFileDialog() class to fetch a video file and write the path as a string in the rich text box. Button 2 takes the value of the rich text box and sends it file to a Python script. This part works fine. Here is the function for sending the file.
I am operating out of Visual Studio 19.
C# .NET framework
public void PotatoOne(string path)
{
var neat = "r'" + path;
var shell = "python.exe";
Process x = new Process();
x.StartInfo = new ProcessStartInfo()
{
FileName = shell,
Arguments = ($"\"{"C:\\Users\\BeckerLab\\source\\repos\\Final Implementation\\Final Implementation\\untitled7.py"}\" \"{neat}\""),
ErrorDialog = true,
WorkingDirectory = Path.GetDirectoryName(#"C:\ProgramData\Anaconda3\envs\tensorflow1"),
UseShellExecute = false,
CreateNoWindow = false,
RedirectStandardError = true,
RedirectStandardOutput = true
};
try
{
x.Start();
var res = x.StandardOutput.ReadToEnd();
var err = x.StandardError.ReadToEnd();
Console.WriteLine(res);
Console.WriteLine();
Console.WriteLine(err);
Console.WriteLine();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.ReadKey();
}
BUT the Process says I do not have some of the modules. Here they all are:
(notably, os, sys, numpy and cv2 are all understood. pandas and PIL, are not)
Python Code, (attempted Anaconda3, tensorflow1 envs)
import os
import cv2
import numpy as np
import sys
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
import PIL
path = sys.argv[1]
I have untitled7.py in its own folder as a python file with its own solution, and they are both using the same Python environments, with the same module patches. Furthermore, untitled7.py has access to all the imports in the regular Python script, but not the .NET process.
It is clear that whatever I am doing, it's not calling the python file to run the same way. Is it because I am calling the Process incorrectly? Do I need to call a virtual environemt? Why can't I call the actual Python environment to run a Python script? Why does the exact same environment not provide the same set of modules for both solutions?
Thank you for your time.
I want to run dask in java process by using jython.
I installed dask[complete] by using pip command.
but, java process raise ImportError: dask
so how I can fix this bug?
package test;
import org.python.core.*;
import org.python.util.*;
public class TestJython {
private static PythonInterpreter pi;
public static void main(String[] args) throws PyException {
pi = new PythonInterpreter();
PySystemState sys = pi.getSystemState();
sys.path.append(new PyString("/usr/local/lib/python2.7/dist-packages"));
pi.exec("import dask.dataframe as dd");
}
}
error log :
Exception in thread "MainThread" Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/local/lib/python2.7/dist-packages/dask/dataframe/__init__.py", line 31, in <module>
raise ImportError(str(e) + '\n\n' + msg)
ImportError: Missing required dependencies ['numpy']
Looks like the PythonInterpreter isn't initialized with the correct PYTHONPATH setup. This is not an issue with Dask, but with how you're initializing PythonInterpreter. Looks like you may need to set the python.path system property, or use the JYTHONPATH environment variable: https://www.stefaanlippens.net/jython_and_pythonpath/.
Note that the dask team has no experience running dask in Jython, and cannot guarantee that things will work, or be performant.
OK, so after searching a little too hard over the internet I still have my same issue. I have a very simple python script that opens up the specified excel file and then runs a macro.
I know for a fact that my python script runs as it should stand alone.
I know for a fact that my C++ code runs as it should.
But the combo of both creates a 'com_error'. Just so anyone who sees this knows, these are all the tests I have ran:
(1) simple python script (just prints hello) --> passed
(2) use C++ to run same simple .py script --> passed
(3) more advanecd python script (opens excel, runs macro, save and close) --> pass
(4) usc C++ code to run advanced .py script --> fail.
And there is my problem. this has something to do with the win32com.client and an error the server throws because it cant find the file location (but trust me it can because it passed the 'find file' test)
I'm running Windows7, Python 2.7, And the latest version of JetBrains Clion (2017.1.2).
Any help would be so appreciated. Thanks! Happy coding.
C++ code:
#include <iostream>
#include <Windows.h>
using namespace std;
int main() {
const char *cmd = "python C:\\Users\\Alex.Valente\\Desktop\\python.py";
PROCESS_INFORMATION processInformation = {0};
STARTUPINFO startupInfo = {0};
startupInfo.cb = sizeof(startupInfo);
BOOL result = CreateProcess(NULL, (LPSTR)cmd,
NULL, NULL, FALSE,
NORMAL_PRIORITY_CLASS,
GetEnvironmentStrings(), NULL, &startupInfo, &processInformation);
if(!result){
return -1;
}
WaitForSingleObject( processInformation.hProcess, INFINITE );
return 0;
}
Python Script:
from __future__ import print_function
import unittest
import os.path
import win32com.client
import os
class ExcelMacro(unittest.TestCase):
def test_excel_macro(self):
xlApp = win32com.client.DispatchEx('Excel.Application')
xlsPath = r'C:\Users\Alex.Valente\Desktop\Data.csv'
xlApp.Visible = True
wb = xlApp.Workbooks.Open(Filename=xlsPath)
xlApp.Run("PERSONAL.XLSB!PythonTest")
wb.Save()
wb.Close()
xlApp.Quit()
print("Macro ran successfully!")
if __name__ == "__main__":
unittest.main()
And the Error that is printed after I run it:
======================================================================
ERROR: test_excel_macro (__main__.ExcelMacro)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Users\Alex.Valente\Desktop\python.py", line 25, in test_excel_macro
wb = xlApp.Workbooks.Open(Filename=xlsPath)
File "<COMObject <unknown>>", line 8, in Open
com_error: (-2147417851, 'The server threw an exception.', None, None)
----------------------------------------------------------------------
Ran 1 test in 6.305s
FAILED (errors=1)