tkinter.TclError: no display name and no $DISPLAY environment variable python - python

I want to execute my python file in a remote system using ssh. I exported the file to the remote system.
Here's the sample file:
import os
import time
import pymsgbox
pymsgbox.alert('Hi Afreeth ', 'Welcome')
if 'DISPLAY' not in os.environ:
pass
I want to execute it using ssh from my system and it should display in the remote system.
But it fails
Error i got:
Traceback (most recent call last):
File "cd1.py", line 5, in <module>
File "pymsgbox/__init__.py", line 100, in alert
File "pymsgbox/__init__.py", line 156, in _buttonbox
File "tkinter/__init__.py", line 1871, in __init__
_tkinter.TclError: no display name and no $DISPLAY environment variable
[12113] Failed to execute script myprogram
How to fix it. I found some answers on stack but it doesn't solve me. If i go and execute it in the remote system, it works. But when i execute from my system,it fails. How to fix it.

Found the Answer:
I just need to run export DISPLAY=:0 in their ssh session and programs run will run on the remote display. A quick example:
paulsteven#smackcoders:~$ ssh afreeth#his_ipaddress
afreeth#smackcoders:~$ export DISPLAY=:0
afreeth#smackcoders:~$ firefox
Firefox is now running on afreeth's display.

Related

Virtual Python enviroment with WINSW

I am trying to create a Windows Service which uses a Virtual Python Environment. I create the environment as described here with venv. To create the Windows Service I use winsw.
While I can both run a program in the virtual environment and setup a windows service I cannot figure out how to do both at once.
My first attempt was to call "call win_env/Scripts/activate.bat" in the .bat file which is used by the windows service. This did not work, as he still used the main enviroment and therefore ignored this line of code. Also the second answer in this issue suggests an solution. This also did not work for me as the program still used the main enviroment.
Possible this is because I do not use the env variables in the code but I cannot figure out how I would start the virtual env from there.
When I write that it uses the "main environment" I track this because the program fails because of some missing dependencies (wrong versions). These dependencies are installed in the virtual environment but not in the main environment. If I call the bat files without going into the virtual environment the program fails with the same message.
Error Message:
Exception in thread {X}:
Traceback (most recent call last):
File "{Path}\scoop\apps\anaconda3\current\lib\threading.py", line 973, in _bootstrap_inner
self.run()
File "{Path}\scoop\apps\anaconda3\current\lib\threading.py", line 910, in run
self._target(*self._args, **self._kwargs)
File "{Path}\Sources\{Project}\.\populate_cache.py", line 25, in query_failures_from_db
df = pd.read_sql(statement, con, params=[date_from, date_to])
File "{Path}\Sources\{Project}\win_env\lib\site-packages\pandas\io\sql.py", line 563, in read_sql
pandas_sql = pandasSQL_builder(con)
File "{Path}\Sources\{Project}\win_env\lib\site-packages\pandas\io\sql.py", line 744, in pandasSQL_builder
import sqlite3
File "{Path}\scoop\apps\anaconda3\current\lib\sqlite3\__init__.py", line 23, in <module>
from sqlite3.dbapi2 import *
File "{Path}\scoop\apps\anaconda3\current\lib\sqlite3\dbapi2.py", line 27, in <module>
from _sqlite3 import *
ImportError: DLL load failed while importing _sqlite3: The specified module could not be found.
.bat file:
call uvicorn main:app --port 8590 --host 0.0.0.0
winsw file:
<?xml version="1.0"?>
<!--This configuration file should be placed near the WinSW executable, the name should be the same.E.g. for myapp.exe the configuration file name should be myapp.xmlYou can find more information about configuration options here: https://github.com/kohsuke/winsw/blob/master/doc/xmlConfigFile.md -->
<configuration>
<id>Test Programm</id>
<name>Test Programm</name>
<description> XXX. </description>
<executable>{PathToBatfile}</executable>
<onfailure delay="10 sec" action="restart"/>
<onfailure delay="20 sec" action="restart"/>
<onfailure action="none"/>
<resetfailure>1 hour</resetfailure>
<workingdirectory>{PathToWorkingdirectory}</workingdirectory> // .bat file is located here
<priority>Normal</priority>
<stoptimeout>15 sec</stoptimeout>
<stopparentprocessfirst>true</stopparentprocessfirst>
<startmode>Automatic</startmode>
<waithint>15 sec</waithint>
<sleeptime>1 sec</sleeptime>
<logpath>{PathToLog}</logpath>
<!--OPTION: logDefines logging mode for logs produced by the executable.Supported modes:* append - Rust update the existing log* none - Do not save executable logs to the disk* reset - Wipe the log files on startup* roll - Rotate logs based on size* roll-by-time - Rotate logs based on time* rotate - Rotate logs based on size, (8 logs, 10MB each). This mode is deprecated, use "roll"Default mode: appendEach mode has different settings.See https://github.com/kohsuke/winsw/blob/master/doc/loggingAndErrorReporting.md for more details -->
<log mode="roll"> </log>
</configuration>
Based on the input you provided, I think the following batch file should work:
call %~dp0win_env/Scripts/activate.bat
uvicorn main:app --port 8590 --host 0.0.0.0
(The %~dp0 resolves to the directory where the batch file is stored, so it works independent of your current working directory.)
Note that the activate.bat does nothing special. It just updates your PATH environment variable and changes the command prompt, which is convenient during development. However, you could also just call the Python executable from your virtual environment without "activating" it. I'm not familiar with uvicorn, but it seems like it can be called as a Python module as well. In that case you could also use the following batch file:
win_env/Scripts/python.exe -m uvicorn main:app --port 8590 --host 0.0.0.0

Pywinauto script compiled as exe using Pyinstaller executes locally but not remotely from the cmd line using PSEXEC

I have a requirement whereby the navigation and control of a legacy application has to be automated - this automated method, packaged as a script, would need to be deployed via SCCM to our user base.
After some research, I've decided to use Python's PywinAuto module to achieve my goal.
I've managed to create a script that automates all the GUI steps as required and I've also packaged this script as an exe using the Pyinstaller module, but the issue i'm now having is the following: when running locally on both Windows 7 and Windows 10 machines, the exe executes successful. However, when triggering the exe remotely through either SCCM or PSEXEC, the exe fails to execute.
I've also wrapped the exe in a powershell script, but the same thing occurs when executing the script via PSEXEC or SCCM.
I'm running PSEXEC as the System user, which has full admin rights. The SCCM user has full admin rights aswell.
This is the Pyinstaller example script that I packaged into an exe, just for testing purpose:
from __future__ import print_function
import logging
from pywinauto import actionlogger
from pywinauto import Application
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--log", help = "enable logging", type=str, required = False)
args = parser.parse_args()
actionlogger.enable()
logger = logging.getLogger('pywinauto')
if args.log:
logger.handlers[0] = logging.FileHandler(args.log)
app = Application(backend='uia').start(r'mspaint.exe')
dlg = app.window(title_re='.* - Paint')
dlg.close()
When running the exe locally from the the command line, the following appears indicating successful execution:
c:\Temp>pywinauto_test 2019-05-11 07:47:14,215 INFO: Started
mspaint.exe application. 2019-05-11 07:47:14,344 INFO: Closed window
"Untitled - Paint"
When running remotely through psexec, the following appears:
C:\Temp>pywinauto_test.exe 2019-05-11 07:29:38,221 INFO: Started
mspaint.exe application. [ 5516] Failed to executC:\Temp>e script
Pywinautopaint Traceback (most recent call last): File
"site-packages\pywinauto\application.py", line 256, in
__resolve_control File "site-packages\pywinauto\timings.py", line 458, in wait_until_passes pywinauto.timings.TimeoutError
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File "Pywinautopaint.py", line
59, in File "site-packages\pywinauto\application.py", line
378, in getattribute File
"site-packages\pywinauto\application.py", line 259, in
__resolve_control File "site-packages\pywinauto\timings.py", line 436, in wait_until_passes File
"site-packages\pywinauto\application.py", line 201, in __get_ctrl
File "site-packages\pywinauto\findwindows.py", line 87, in
find_element pywinauto.findwindows.ElementNotFoundError: {'title_re':
'.* - Paint', 'backend': 'uia', 'process': 2844}
All known methods to run GUI automation remotely are listed in the Remote Execution Guide. It's not specific to PyInstaller or other py2exe-like tools. Mostly it's OS Windows restrictions and RDP features that can be workarounded by several ways.
Also ElementNotFoundError is often raised when default timeout to find window (5 sec.) is insufficient. For example, if remote virtual machine is slow. This might be unrelated to common remote execution problems.

Debugging in PyCharm with using Vagrant VM connection - cannot import name to_string

I've encountered an issue where I cannot debug in PyCharm connecting through Vagrant to the VM. This has worked fine for projects up until now. The VM image was recently updated so I'm wondering if that has had an effect. I can run programs in "run" mode, just not debug mode. Here's the error I get
Traceback (most recent call last):
File "/home/vagrant/.pycharm_helpers/pydev/pydevd.py", line 25, in <module>
from _pydevd_bundle import pydevd_vars
File "/home/vagrant/.pycharm_helpers/pydev/_pydevd_bundle/pydevd_vars.py", line 21, in <module>
from _pydevd_bundle.pydevd_utils import to_string
ImportError: cannot import name to_string
Here are the different commands used to run the programs - the first one is debug mode, the second is normal mode
ssh://vagrant#127.0.0.1:2222/usr/bin/python -u /home/vagrant/.pycharm_helpers/pydev/pydevd.py --multiproc --qt-support --client '0.0.0.0' --port 32807 --file /home/vagrant/.pycharm_helpers/pycharm/utrunner.py /vagrant/project/project_test.py::ProjectTest true
ssh://vagrant#127.0.0.1:2222/usr/bin/python -u /home/vagrant/.pycharm_helpers/pycharm/utrunner.py /vagrant/project/project_test.py::ProjectTest true
Any ideas what why to_string is found in normal mode but not debug?
The solution was to delete the /home/vagrant/.pycharm_helpers directory and restart PyCharm and vagrant to regenerate the directory.

Import error with remote interpreter in pycharm

I am trying to run my code in the server using ssh remote interpreter.
The connection and the deployment work but when I want to import libraries located in the server it gives an import error
ssh://***#****.com:22/usr/bin/python -u
/home//main.py Traceback
(most recent call last): File
"/home//main.py", line 11,
in
from clplibs.clp import ContinuousLearningPlatform as clp ImportError: No module named clplibs.clp
Process finished with exit code 1
I've found a solution, the environment variables (including python path) should be defined from pycharm: Run/Debug configurations-> Environment variables. Pycharm won't use bashrc paths.

Running Linux Commands from Python on Windows Computer

I am trying to learn how to run command line commands from Python. I am able to do this with DOS:
import subprocess
subprocess.call("dir",shell=True)
This is fine, but I need to be able to do this for linux commands because my company uses linux servers. I am using Mobaxterm to run a local linux session. When I try this:
import subprocess
subprocess.call("ls",shell=True)
I get this error from the terminal:
'ls' is not recognized as an internal or external command, operable program or batch file.
Which sounds ridiculous to me, because ls is clearly a linux command.
If I don't include shell=True I get this error:
Traceback (most recent call last):
File "ConsolePractice.py", line 4, in <module>
subprocess.call("ls")
File "C:\Users\my_username\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 560, in call
with Popen(*popenargs, **kwargs) as p:
File "C:\Users\my_username\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 950, in __init__
restore_signals, start_new_session)
File "C:\Users\my_username\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 1220, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
So what am I doing wrong? How can I get this to work?
EDIT: Thanks for the comments. Python for Windows won't work for what I'm trying to do. I connected to a linux server and did:
cat > ConsoleCmd.py
import subprocess
subprocess.call("ls",shell=True)
^C
python ConsoleCmd.py
... and ls ran. Found the issue. I'll just have to get my scripts on to the server and run them from there. Thanks everyone
I was able to resolve this issue by opening an SFTP Session within Mobaxterm, transferring the python file to the server, then running the file directly on the server (python was already installed on the server).

Categories