I am trying to send commands to the Vte terminal but I keep getting the same error. Also, I could not find any other working examples on the internet. Since my code is not complete at the moment, I am showing you an example from stackoverflow. It gives the same error.
Error message :
File "~/basic-terminal/terminal.py", line 52, in InputToTerm
self.terminal.feed_child(self.command, length)
TypeError: Vte.Terminal.feed_child() takes exactly 2 arguments (3 given)
The code :
from gi.repository import Gtk, GObject, Vte
#GObject is not required. I just import it everywhere just in case.
#Gtk, Vte, and GLib are required.
from gi.repository import GLib
import os
#os.environ['HOME'] helps to keep from hard coding the home string.
#os is not required unless you want that functionality.
class TheWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title="inherited cell renderer")
self.set_default_size(600, 300)
self.terminal = Vte.Terminal()
self.terminal.fork_command_full(
Vte.PtyFlags.DEFAULT, #default is fine
os.environ['HOME'], #where to start the command?
["/bin/sh"], #where is the emulator?
[], #it's ok to leave this list empty
GLib.SpawnFlags.DO_NOT_REAP_CHILD,
None, #at least None is required
None,
)
#Set up a button to click and run a demo command
self.button = Gtk.Button("Do The Command")
#To get the command to automatically run
#a newline(\n) character is used at the end of the
#command string.
self.command = "echo \"Sending this command to a virtual terminal.\"\n"
command = Gtk.Label("The command: "+self.command)
self.button.connect("clicked", self.InputToTerm)
#end demo command code
#set up the interface
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
box.pack_start(self.button, False, True, 0)
box.pack_start(command, False, True, 1)
#a scroll window is required for the terminal
scroller = Gtk.ScrolledWindow()
scroller.set_hexpand(True)
scroller.set_vexpand(True)
scroller.add(self.terminal)
box.pack_start(scroller, False, True, 2)
self.add(box)
def InputToTerm(self, clicker):
#get the command when the button is clicked
length = len(self.command)
#A length is not required but is the easiest mechanism.
#Otherwise the command must be null terminated.
#Feed the command to the terminal.
self.terminal.feed_child(self.command, length)
win = TheWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()
What can i do ? Why am I constantly getting this error ?
solved the problem. the command has changed. You can also solve your problem this way :)
self.terminal.feed_child(self.command.encode("utf-8"))
Related
I'm fairly new to rust and have been following the official book that they provide on their site. During chapter 2 they tell you to import a "Rand" cargo which I did. However, when I try to run my code directly through VS Code I get an error saying "unresolved import rand". When I run it through command prompt, everything works fine. I've already tried every solution suggested here: https://github.com/rust-lang/rls-vscode/issues/513 and nothing seemed to have worked. Extensions that I'm using:
Better TOML
Cargo
Code Runner
Rust (rls)
Rust Assist
vsc-rustfmt
vscode-rust-syntax
Has anyone else ran into a similar problem or a know a solution? Thank you!
Edit: My Cargo.TOML looks like this:
[package]
name = "guessing_game"
version = "0.1.0"
authors = ["Name <MyNameHere#gmail.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
rand = "0.6.0"
Edit 2: my main.rs file looks like this:
use rand::Rng;
use std::io;
use std::cmp::Ordering;
fn main()
{
println!("Guess the number!");
let secret_number = rand::thread_rng().gen_range(1, 101);
loop
{
println!("Please input your guess!");
let mut guess = String::new();
io::stdin().read_line(&mut guess).expect("Failed to read line!");
let guess: u32 = match guess.trim().parse()
{
Ok(num) => num,
Err(_) => continue,
};
println!("Your guess {}", guess);
match guess.cmp(&secret_number)
{
Ordering::Less => println!("Too small!"),
Ordering::Greater => println!("Too big!"),
Ordering::Equal =>
{
println!("You win!");
break;
}
}
}
}
Got a fix!
In VSC, select Extensions, select the Code Runner extension, click the little gear symbol and select Extension Settings. It's the Code-runner: Executor Map setting that needs to be changed. Click the 'Edit in settings.json' link.
Add the following to the file:
"code-runner.executorMap": {
"rust": "cargo run # $fileName"
}
If you already have content in the settings.json file then remember to add a comma to the line above and put your edit inside the outermost curly braces, e.g.
{
"breadcrumbs.enabled": true,
"code-runner.clearPreviousOutput": true,
"code-runner.executorMap": {
"rust": "cargo run # $fileName"
}
}
This tells Code Runner to use the 'cargo run' command, instead of 'rustc'
This fix came from this question on stackoverflow.
So I have some code which uses xlwings for writing data in Excel file, xlsm.
after i've done writing, I press a certain button to calculate.
sometimes, an error/message pops in the Excel, which is fine, but i want to catch this message to python, and write it later to a log/print it.
also, i need to interact with this message, in this case to press "Ok" in the message box
Attached image of the message box
So guys, I've been able to solve this with an external python library.
here is the code:
from pywinauto import application as autoWin
app = autoWin.Application()
con = app.connect(title = 'Configuration Error')
msgText = con.Dialog.Static2.texts()[0]
con.Dialog.Button.click()
con.Dialog.Button.click()
print(msgText)
basically, what it does, is connecting to the app, and searching for the title.
in this case "Configuration Error"
it needs to perform double click in order to press "Ok" to close the message.
Secondly, it gets the text from the message, and can forward it wherever i want.
important part to remember though, because this should be an automated task, it should run concurrently, which means Threading.
so, a simple Thread class below:
class ButtonClicker(Thread):
def __init__(self):
Thread.__init__(self)
self._stop_event = Event()
def stop(self):
self._stop_event.set()
def stopped(self):
return self._stop_event.is_set()
def run(self) -> None:
while True:
time.sleep(3)
try:
app = autoWin.Application()
con = app.connect(title='Configuration Error')
msg_data = con.Dialog.Static2.texts()[0]
while True:
con.Dialog.Button.click()
# con.Dialog.Button.click()
# print(msg_data)
return msg_data
except Exception as e:
print('Excel didnt stuck')
break
and of course to actually use it:
event_handle = ButtonClicker()
event_handle.start()
some manipulation is needed in order to work in different codes/scenarios, but at least I hope i will help others in the future, because this seems to be very common question.
#Danny's solution, i.e. pywinauto and Thread, works perfectly in my local machine, but it seems can't catch the message box when Excel is running in server mode, e.g. in my case, the automation is triggered in local and started by a system service installed in the server.
pywinauto.findwindows.ElementNotFoundError:
{'title': '<my-wanted-title>', 'backend': 'win32', 'visible_only': False}
It is finally solved with another python third-party library pywin32, so providing a backup solution here.
'''
Keep finding message box with specified title and clicking button to close it,
until stopped by the main thread.
'''
import time
from threading import Thread, Event
import win32gui
import win32con
class ButtonClicker(Thread):
def __init__(self, title:str, interval:int):
Thread.__init__(self)
self._title = title
self._interval = interval
self._stop_event = Event()
def stop(self):
'''Stop thread.'''
self._stop_event.set()
#property
def stopped(self):
return self._stop_event.is_set()
def run(self):
while not self.stopped:
try:
time.sleep(self._interval)
self._close_msgbox()
except Exception as e:
print(e, flush=True)
def _close_msgbox(self):
# find the top window by title
hwnd = win32gui.FindWindow(None, self._title)
if not hwnd: return
# find child button
h_btn = win32gui.FindWindowEx(hwnd, None,'Button', None)
if not h_btn: return
# show text
text = win32gui.GetWindowText(h_btn)
print(text)
# click button
win32gui.PostMessage(h_btn, win32con.WM_LBUTTONDOWN, None, None)
time.sleep(0.2)
win32gui.PostMessage(h_btn, win32con.WM_LBUTTONUP, None, None)
time.sleep(0.2)
if __name__=='__main__':
t = ButtonClicker('Configuration Error', 3)
t.start()
time.sleep(10)
t.stop()
I got an issue with Gtk.
My code is compiling with no error, but only the windows with its title is appearing.
So I wondered if I made something wrong and tried some examples of the documentation (see below).
And it didn't worked either.
I updated the packages, rm, and add again, no error.
No error in compiling, nothing.
When I ask if the widgets are visible it is saying yes.
I saw that it could be a configuration problem of gtk but with no more explanation.
Thank you for your help !
using Gtk
ls = GtkListStore(String, Int, Bool, Bool)
push!(ls,("Peter",20,false,true))
push!(ls,("Paul",30,false,true))
push!(ls,("Mary",25,true,true))
insert!(ls, 2, ("Susanne",35,true,true))
rTxt = GtkCellRendererText()
rTog = GtkCellRendererToggle()
c1 = GtkTreeViewColumn("Name", rTxt, Dict([("text",0)]), sort_column_id=0)
c2 = GtkTreeViewColumn("Age", rTxt, Dict([("text",1)]), sort_column_id=1)
c3 = GtkTreeViewColumn("Female", rTog, Dict([("active",2)]), sort_column_id=2)
tmFiltered = GtkTreeModelFilter(ls)
GAccessor.visible_column(tmFiltered,3)
tv = GtkTreeView(GtkTreeModel(tmFiltered))
push!(tv, c1, c2, c3)
selection = GAccessor.selection(tv)
signal_connect(selection, "changed") do widget
if hasselection(selection)
currentIt = selected(selection)
println("Name: ", GtkTreeModel(tmFiltered)[currentIt,1],
" Age: ", GtkTreeModel(tmFiltered)[currentIt,1])
end
end
ent = GtkEntry()
signal_connect(ent, "changed") do widget
searchText = get_gtk_property(ent, :text, String)
for l=1:length(ls)
showMe = true
if length(searchText) > 0
showMe = showMe && occursin(lowercase(searchText), lowercase(ls[l,1]))
end
ls[l,4] = showMe
end
end
vbox = GtkBox(:v)
push!(vbox,ent,tv)
win = GtkWindow(vbox, "List View with Filter")
showall(win)
I tried it, but run as a file, your app closes so fast you do not see it display at all. This is covered in the Gtk.jl docs under "Non REPL Usage" ie running as a file, outside the julia REPL command line. Just replace showall(win) with:
condition = Condition()
endit(w) = notify(condition)
signal_connect(endit, win, :destroy)
showall(win)
wait(condition)
The app will then pass control to the internal Gtk runtime event loop and wait for the app to close. I was able to run your app and see the check boxes fine with this. If you cannot, you might have a problem with your local files.
I am trying to create test runner python file, that executes the pytest.exe in particular testcase folder and send the results via email.
Here is my code:
test_runner.py:
try:
command = "pytest.exe {app} > {log}".format(app=app_folder, log = log_name)
os.system(command)
except:
send_mail()
I use the following code in conftest.py to add screenshots to pytest-html report.
In conftest.py:
#pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
pytest_html = item.config.pluginmanager.getplugin('html')
outcome = yield
report = outcome.get_result()
extra = getattr(report, 'extra', [])
if pytest_html:
xfail = hasattr(report, 'wasxfail')
if (report.skipped and xfail) or (report.failed and not xfail):
test_case = str(item._testcase).strip(")")
function_name = test_case.split(" ")[0]
file_and_class_name = ((test_case.split(" ")[1]).split("."))[-2:]
file_name = ".".join(file_and_class_name) + "." + function_name
Issue is, when I run the command "pytest.exe app_folder" in windows command prompt it is able to discover the test cases and execute them and get the results. But when I call the command from .py file either using os.command or subprocess it fails with the following exception:
\conftest.py", line 85, in pytest_runtest_makereport
INTERNALERROR> test_case = str(item._testcase).strip(")")
INTERNALERROR> AttributeError: 'TestCaseFunction' object has no attribute
'_testcase'
Can anyone please help me to understand whats happening here? or any other way to get the testcase name?
Update:
To overcome this issue, I alternatively used the TestResult object from pytest_runtest_makereport hook to get the test case details.
#pytest.mark.hookwrapper
def pytest_runtest_makereport(item, call):
outcome = yield
report = outcome.get_result()
In the above example, report variable contain the TestResult object. This can be manipulated to get the testcase/class/module name.
you can use shell=True option with subprocess to get the desired result
from subprocess import Popen
command='pytest.exe app_folder' #you can paste whole command which you run in cmd
p1=Popen(command,shell=True)
This would solve your purpose
I have found ways to make pocketsphinx activate using multiple keywords, but I want to run diffrent commands depending on which keyword was said. I have already made it connect to Amazon's Alexa server when "Alexa" is said and now I want to add a command when I say "TV Off" and "TV On."
The best thing is to use python, something like this:
import sys, os
from pocketsphinx.pocketsphinx import *
from sphinxbase.sphinxbase import *
import pyaudio
modeldir = "../../../model"
# Create a decoder with certain model
config = Decoder.default_config()
config.set_string('-hmm', os.path.join(modeldir, 'en-us/en-us'))
config.set_string('-dict', os.path.join(modeldir, 'en-us/cmudict-en-us.dict'))
config.set_string('-kws', 'keyword.list')
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paInt16, channels=1, rate=16000, input=True, frames_per_buffer=1024)
stream.start_stream()
# Process audio chunk by chunk. On keyword detected perform action and restart search
decoder = Decoder(config)
decoder.start_utt()
while True:
buf = stream.read(1024)
if buf:
decoder.process_raw(buf, False, False)
else:
break
if decoder.hyp() == "tv on":
print ("Detected keyword tv on, turning on tv")
os.system('beep')
decoder.end_utt()
decoder.start_utt()
if decoder.hyp() == "tv off":
print ("Detected keyword tv off, turning off tv")
os.system('beep beep')
decoder.end_utt()
decoder.start_utt()