I want to run a python script from Qt, when the user clicks a button. This script works properly in a terminal but I get an error when I execute from Qt.
I have tried to execute the script from Pycharm IDE and I get the same error:
Traceback (most recent call last):
File "/home/ana/PycharmProjects/Gurobi/one_set.py", line 1, in <module>
from gurobipy import *
File "/usr/local/lib/python2.7/dist-packages/gurobipy/__init__.py", line 1, in <module>
from .gurobipy import *
ImportError: libgurobi81.so: cannot open shared object file: No such file or directory
When I execute "import gurobipy" in a python console, I get no error.
import gurobipy
import pkg_resources
pkg_resources.get_distribution("gurobipy").version
'8.1.1'
Searching libgurobi81.so, I check that this file exists in:
/opt/gurobi811/linux64/lib/libgurobi81.so
/usr/lib/python2.7/dist-packages/gurobi811/linux64/lib/libgurobi81.so
/usr/local/lib/python2.7/dist-packages/gurobipy/libgurobi81.so
As suggested in install instructions, I have included environment variables in /home/usr/.bashrc as:
export GUROBI_HOME="/opt/gurobi811/linux64"
export PATH="${PATH}:${GUROBI_HOME}/bin"
export LD_LIBRARY_PATH="${GUROBI_HOME}/lib"
I also included the other directories that contain libgurobi81.so:
export PATH=$PATH:/usr/lib/python2.7/dist-packages/gurobi811/
export PATH=$PATH:/usr/local/lib/python2.7/dist-packages/gurobipy/
However, from terminal everything works fine and I get the solution:
/usr/bin/python2.7 /home/ana/PycharmProjects/Gurobi/one_set.py
Academic license - for non-commercial use only
instance objVal time
Instance1.csv 0.030176 0.0002670288
[1 rows x 2 columns]
The code I use to run python script from Qt is:
QString command("/usr/bin/python2.7");
QStringList params = QStringList() << "/home/ana/PycharmProjects/Gurobi/one_set.py";
QProcess *process = new QProcess();
process->startDetached(command, params);
process->waitForFinished();
qDebug()<<process->readAllStandardOutput();
process->close();
I expected the same output from Qt as from terminal, since the command I use to run it is the same:
/usr/bin/python2.7 /home/ana/PycharmProjects/Gurobi/one_set.py
Solved. The solution was adding environment variables before the start of the process:
QString command("/usr/bin/python2.7");
QStringList params = QStringList();
params.append("/home/ana/PycharmProjects/Gurobi/one_set.py");
QProcess *process = new QProcess();
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
env.insert("LD_LIBRARY_PATH", "/usr/local/lib:/opt/gurobi811/linux64/lib:/opt/gurobi811/linux64/lib:/opt/gurobi811/linux64/lib/"); // Add an environment variable
process->setProcessEnvironment(env);
process->start(command, params);
process->waitForFinished();
QString p_stdout = process->readAllStandardOutput();
ui->Output->setText(p_stdout);
process->close();
Related
I'm facing quite simple problem, yet still not able to figure out what in particular causes that, and - more importantly - how to solve it.
I'm currently on Linux, and I would like to run an python app (script) from a Java application. The script is on PATH, thus I really would like to utilise that (avoid using absolute path to the script), if possible.
However, all I tried resulted in various forms of "File does not exist".
Sample
As a demonstration, I've tried to run one python3-based app (meld)
and one binary-built app (ls) for comparison:
$ which ls
/usr/bin/ls
$ file /usr/bin/ls
/usr/bin/ls: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, BuildID[sha1]=[...], for GNU/Linux 3.2.0, stripped
$ which meld
/usr/bin/meld
$ file /usr/bin/meld
/usr/bin/meld: Python script, UTF-8 Unicode text executable
$ head -n1 /usr/bin/meld
#!/usr/bin/python3
Nextly, I've created simple Java main, which tries several ways how to start theese:
package cz.martlin.processes;
import java.io.File;
import java.io.IOException;
import java.lang.ProcessBuilder.Redirect;
import java.util.List;
import java.util.stream.Collectors;
public class ProcessPlaying {
public static void main(String[] args) {
List<List<String>> commands = List.of(
List.of("ls"),
List.of("/usr/bin/ls"),
List.of("meld"),
List.of("/usr/bin/meld"),
List.of("python3", "/usr/bin/meld"),
List.of("/usr/bin/python3", "/usr/bin/meld"),
List.of("sh", "-c", "meld"),
List.of("sh", "-c", "/usr/bin/meld"),
List.of("sh", "-c", "python3 /usr/bin/meld")
);
for (List<String> command : commands) {
run(command);
}
}
private static void run(List<String> command) {
System.out.println("Running: " + command);
//String executable = command.get(0);
//boolean exists = new File(executable).exists();
//System.out.println("Exists the " + executable + " ? " + exists);
try {
ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectError(Redirect.INHERIT);
Process proc = pb.start();
// Process proc = Runtime.getRuntime().exec(command.stream().collect(Collectors.joining(" ")));
int code = proc.waitFor();
System.out.println("OK, return code: " + code);
} catch (IOException e) {
System.out.println("Failed to start: " + e.toString());
} catch (InterruptedException e) {
System.out.println("Failed to await: " + e.toString());
}
System.out.println();
}
}
Here are the results:
Running: [ls]
OK, return code: 0
Running: [/usr/bin/ls]
OK, return code: 0
Running: [meld]
Failed to start: java.io.IOException: Cannot run program "meld": error=2, Directory or file doesn't exist
Running: [/usr/bin/meld]
Failed to start: java.io.IOException: Cannot run program "/usr/bin/meld": error=2, Directory or file doesn't exist
Running: [python3, /usr/bin/meld]
python3: can't open file '/usr/bin/meld': [Errno 2] No such file or directory
OK, return code: 2
Running: [/usr/bin/python3, /usr/bin/meld]
/usr/bin/python3: can't open file '/usr/bin/meld': [Errno 2] No such file or directory
OK, return code: 2
Running: [sh, -c, meld]
sh: line 1: meld: command not found
OK, return code: 127
Running: [sh, -c, /usr/bin/meld]
sh: line 1: /usr/bin/meld: Directory or file doesn't exist
OK, return code: 127
Running: [sh, -c, python3 /usr/bin/meld]
python3: can't open file '/usr/bin/meld': [Errno 2] No such file or directory
OK, return code: 2
To sum it up:
all of the commands tried works when executed directly from the shell (either sh or bash)
executing the binary works either by the full path (/usr/bin/ls) or by just the name (ls)
executing the python script the same way doesn't work neither way
when trying to run the python3 interpreter and populate the script path as an argument to the python, now the python yields the script file doesn't exist
trying to populate it as a command to the brand new shell didn't help either
I've tried to use the Runtime#exec (based on this comment: https://stackoverflow.com/a/36783743/3797793) to start the process (both the exec(String) and exec(String[] forms), but no sucess (none of the listed commands did actually execute).
Thus, my question is/are:
What do I understand wrong?
How to start the Python script from Java?
Would some small (ba)sh script wrapper do the job?
Since it's python3-based, Jython wouldn't help here (because the latest one is 2.7.*), would it?
Further requirements:
As mentioned, I would like to be able to avoid using full path to the Python script
Also, I would like to have platform independant solution (at least Linux and Windows compatible)
Thanks in advance
I have a script, let's call it /home/pi/somescript.py and when I call it with /bin/python3.7 /home/pi/somescript.py everything works as it should.
Now I'm trying to call from a php script with exec('/bin/python3.7 /home/pi/somescript.py', $output, $ret_code);. This however throws a ModuleNotFoundError.
But when I run the interactive PHP shell and paste the above exec in there, it also works. Am I missing something? What could be the cause of this? How do I fix this?
The relevant part of the python script:
import sys
sys.stderr = sys.stdout # so I get the stacktrace in the $output of the php file
from iso3166 import countries # <- error here
# ...
I'm running a lighttpd server. The PHP file lies in /var/www/html/info.php and I access it via a browser with http://raspberrypi:8080/info.php
The relevant part of the PHP file:
exec('/bin/python3.7 /home/pi/somescript.py', $output, $ret_code);
$data = ["out" => $output];
header('Content-Type: application/json');
echo json_encode($data);
// this way I get the output when in the browser
The stacktrace I get:
Traceback (most recent call last):
File "/home/pi/somescript.py", line 6, in <module>
from iso3166 import countries
ModuleNotFoundError: No module named 'iso3166'
I have a python file(file1.py) where i have written a script. Now, my friend asked me to keep the inputs in another python file(file2.py) and import the file in file1.py so that its becomes easy to modify the inputs if we keep it seperate file. So i created file2.py, copied the inputs there and saved it. Then i wrote the following line in file1.py: from file2 import * but its throwing error:
TASK [Run the python script]
********************************************************************************************************************************************************************************************************************************* fatal: [automation_server]: FAILED! => {"changed": true, "msg":
"non-zero return code", "rc": 1, "stderr": "Shared connection to
10.242.174.192 closed.\r\n", "stderr_lines": ["Shared connection to 10.242.174.192 closed."], "stdout": "/etc/profile.d/lang.sh: line 19: warning: setlocale: LC_CTYPE: cannot change locale (UTF-8): No such
file or directory\r\nTraceback (most recent call last):\r\n File
\"/home/bgnanasekaran/.ansible/tmp/ansible-tmp-1591957555.760499-407
182191177023663/download_RI_build.py\", line 8, in \r\n
from file2 import
*\r\nModuleNotFoundError: No module named 'file2'\r\n", "stdout_lines": ["/etc/profile.d/lang.sh: line 19: warning: setlocale:
LC_CTYPE: cannot change locale (UTF-8): No such file or directory",
"Traceback (most recent call last):", " File
\"/home/bgnanasekaran/.ansible/tmp/ansible-tmp-1591957555.760499-407
182191177023663/download_RI_build.py\", line 8, in ", "
from file2 import *", "ModuleNotFoundError: No module named 'file2'"]}
Note: I'll give some example of inputs in file2.py -
name="Suresh"
college="VIT"
Also note: I wrote all these python scripts to make it run with ansible playbook. This script is a part of play in my ansible playbook.
Please help me do this. I want a python file where i can store my python script inputs and use the same file in python script. This is not so related to ansible but more related to python.
you need a configuration file this post might help you or you can create a class and all required variable as a class variable and import the class into your script.
import is for python files only.
If you want to read content of a file you need to open it.
with open('filename', 'r') as handler:
print(handler.readlines())
Is a minimal example
You could also try to use environment varibales, which is a much more common practice when dealing with deployment strategies
import os
VARIABLE = os.getenv('VARIBALE', 'default_value')
Then you run the script with:
VARIABLE=this ./pythonscript.py
Or export the variable into the environment in another way
I am working on creating a WebGL interface for which I am trying to convert FBX models to JSON file format in an automated process using python file, convert_fbx_three.py (from Mr. Doob's GitHub project) from command line.
When I try the following command to convert the FBX:
python convert_fbx_three.py Dolpine.fbx Dolpine
I get following errors:
Error in cmd:
Traceback (most recent call last):
File "convert_fbx_three.py", line 1625, in <module>
sdkManager, scene = InitializeSdkObjects()
File "D:\xampp\htdocs\upload\user\fbx\FbxCommon.py", line 7, in InitializeSdkObjects
lSdkManager = KFbxSdkManager.Create()
NameError: global name 'FbxManager' is not defined
I am using Autodesk FBX SDK 2012.2 available here on Windows 7.
Can you please try the following:
import FbxCommon
.
.
.
lSdkManager, lScene = FbxCommon.InitializeSdkObjects()
You probably need to add environment variables pointing to the folder that contains fbx.pyd, FbxCommon.py, and fbxsip.pyd prior to calling anything in those modules.
I found a way to run built in auto it functions from python using the following code
from win32com.client import Dispatch
Auto = Dispatch("AutoItX3.Control")
Auto.Run("notepad.exe", "", 5)
Is there a similar way to call custom methods i.e methods defined in my_AutoIt_File.au3
Say I have a method in this file
Func my_autoit_method
;some code
EndFunc
Is there a way to call this my_autoit_method from python?
From the help file:
AutoIt specific command Line Switches
Form1: AutoIt3.exe [/ErrorStdOut] [/AutoIt3ExecuteScript] file
[params ...]
Execute an AutoIt3 Script File
/ErrorStdOut Allows to redirect fatal error to StdOut which can be captured by an application as Scite editor. This switch can be used with a compiled script.
To execute a standard AutoIt Script File 'myscript.au3', use the command:
'AutoIt3.exe myscript.au3'
Form2: Compiled.exe [/ErrorStdOut] [params ...]
Execute an compiled AutoIt3 Script File produced with Aut2Exe.
Form3: Compiled.exe [/ErrorStdOut] [/AutoIt3ExecuteScript file]
[params ...]
Execute another script file from a compiled AutoIt3 Script File. Then you don't need to fileinstall another copy of AutoIT3.exe in your compiled file.
Form4: AutoIt3.exe [/ErrorStdOut] /AutoIt3ExecuteLine "command line"
Execute one line of code.
To execute a single line of code, use the command:
Run(#AutoItExe & ' /AutoIt3ExecuteLine "MsgBox(0, ''Hello World!'', ''Hi!'')"')
You have to expose your AutoIt Function to other applications. This could be done easily with AutoItObject, which can register an object in the ROT.
The AutoIt Code would be:
#include <AutoItObject.au3>
$oObject = _AutoItObject_Create()
_AutoItObject_RegisterObject($oObject, 'MyVery.CustomApplication')
_AutoItObject_AddMethod($oObject, '_my_custom_function', '_my_custom_function')
While Sleep(100)
WEnd
Func _my_custom_function($oSelf)
MsgBox(0, '', 'AutoIt says Hi')
Exit
EndFunc
The Python Code should be:
from win32com.client import Dispatch
Auto = Dispatch("MyVery.CustomApplication")
Auto._my_custom_function()