My python script has two main steps:
Open two webbrowser tabs (default browser). And let a LED blink.
When i am executing the python script via shell with "python netflix.py" everything works fine.
But when i am trying to start it via my (see below) NodeJS script. Only the LED will be blink. The webbrowser tabs won't come up.
Does anyone know where the issue is?
#!/usr/bin/env node
process.env.UV_THREADPOOL_SIZE = 1208;
var http = require('http');
const server = http.createServer(function(request, response) {
try{
console.log('Request incoming...');
var spawn = require('child_process').spawn;
if(request.url == '/abort'){
console.log('Calling abort.py ...');
var process = spawn('python',["./abort.py"]);
}else{
console.log('Calling netflix.py');
var process = spawn('python',["./netflix.py"]);
}
}catch(e){
console.log('Error');
console.log(e);
}
});
server.on('error', function(){
console.log('error');
});
const port = 8000;
server.listen(port);
server.timeout = 10000;
console.log(`Listening at http://leitner-pi:${port}`);
import sys
import webbrowser
from gpiozero import LED
from time import sleep
try:
webbrowser.open_new_tab("http://netflix.com");
finally:
print("")
print("Lasse PIN 7 blinken..")
led = LED(17)
while True:
led.on()
sleep(0.3)
led.off()
sleep(0.3)
Fixed: Well, I made a workaround.
First, I split the python script into two scripts. Webbrowser and LED script, to avoid any kind of interruptions or something else. Second, I changed the webbrowser to:
os.system(‘sudo -upi chromium-browser URL1 URL2’).
At last, I am calling both new
scripts from my node webserver, like I used before.
Now it works fine.
Related
I am trying to configure python on my arduino. Ive followed like 10 tutorials but none of them are working. Ive tried to connect via pyserial. When I use pyserial, I simply get no response, here is the code.
I am trying to process data and code in python, then send data to arduino to run. I already downloaded the Firmata libraries on both, no issues there. I have also uploaded the arduino standard firmata sketch, no issues there.
Code being run on my python ide:
import serial
import time
Arduino = serial.Serial('com5',115200)
time.sleep(5)
while True:
while (Arduino.inWaiting()==0):
print("ur dumb")
pass
dataPacket = Arduino.readline()
print(dataPacket)
Code being run on my Arduino IDE:
int count = 1;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
}
void loop() {
// put your main code here, to run repeatedly:
Serial.print(count);
delay(1000);
count = count+1;
}
Similary I've tried:
import pyfirmata
import time
board = pyfirmata.Arduino('/dev/ttyACM0')
it = pyfirmata.util.Iterator(board)
it.start()
digital_input = board.get_pin('d:10:i')
led = board.get_pin('d:13:o')
while True:
sw = digital_input.read()
if sw is True:
led.write(1)
else:
led.write(0)
time.sleep(0.1)
you can use a more accessible python program here to work:
import serial
import time
ArduinoUnoSerial = serial.Serial('com5',115200)
while 1:
print (ArduinoUnoSerial.readline())
this will work with your Arduino program
don't worry about the board no matter whether it is mega or uno or anything else ArduinoUnoSerial.readline() will work
I am creating a vscode extension where I need machine learning tasks to be performed. I have python files that have code that is required in vscode extension. I don't want things to be done using request-response on any python server. What I want is to perform the ML tasks on device (integrated with the vsix).
We have child-process available in js to run basic python file using spawn. It is running fine on both, extension host window and external vscode editor after packaging, with the python code that has basic imports like import sys. But if I try to import some other libraries like numpy, pygments, it is working only on extension host environment, not on other vs window after packaging it. How can I run the typical python code with the vsix?
Below are both the codes that is working fine and not working at all-
TS file (MLOps.ts)-
import { ChildProcessWithoutNullStreams, spawn } from "child_process";
import { join } from "path";
import * as vscode from 'vscode'
export async function pythonOps(): Promise<string> {
var result = "testt"
var promise = await new Promise((resolve, reject) => {
var p = __dirname.split('\\')
p.pop()
var path = p.join('\\')
var pyPath = join(path, 'src', 'py_operations.py')
var result = "blank result"
var arg1 = "arg one"
var arg2 = "arg two"
var py_process = spawn('python', [pyPath, arg1, arg2])
py_process.stdout.on('data', (data: any) => {
vscode.window.showInformationMessage(data.toString())
result = data.toString()
})
})
}
Working Python code (py_operations.py)- This code is working on both, on extension host window and after packaging the extension and installing the vsix on other system.
import sys
print("Some text with: ",sys.argv[0], sys.argv[1], sys.argv[2])
sys.stdout.flush()
Not working Python code- This code is working only on extension host window, and not working after packaging this and isntalling on other system.
import sys
from pygments.lexers.javascript import TypeScriptLexer
lexer = TypeScriptLexer()
src = "alert('text here')"
lexer_tokens = lexer.get_tokens(src)
l = []
for t in lexer_tokens:
l.append(t[1])
print("list: ",l)
sys.stdout.flush()
How can I run the second python code with packaged vsix?
Currently I have a very basic js and python script.
The problem is that the python text is not displayed after running the JS file in the CMD.
I am working in Windows 10 OS.
Does someone see what I am doing wrong?
var spawn = require('child_process').spawn;
var child = spawn('python3', ['hello.py']);
child.stdout.on('data', (data) => {
console.log(data.toString());
});
-->
Python Code for testing:
import sys
data = "hallo hallo test"
print(data)
sys.stdout.flush()
I've created a DotNet Core Razor MVC project and in there, I have created a directory called python. Within that python directory, I have created a python script called myscript.py.
Following the real-time chat example for SignalR, I have added a function to my ChatHub which is supposed to execute myscript.py:
private string ProcessMessage(string message)
{
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = "/Users/SomeUser/Documents/Code/VisualStudio/MyProject/MyProject/python/myscript.py";
start.Arguments = message;
start.UseShellExecute = false;// Do not use OS shell
start.CreateNoWindow = true; // We don't need new window
start.RedirectStandardOutput = true;// Any output, generated by application will be redirected back
start.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions)
using (Process process = Process.Start(start))
{
using (StreamReader reader = process.StandardOutput)
{
string stderr = process.StandardError.ReadToEnd(); // Here are the exceptions from our Python script
string result = reader.ReadToEnd(); // Here is the result of StdOut(for example: print "test")
return result;
}
}
}
Notice I have provided the full path to start.FileName. However, when I run this, I get a permission denied error.
I've tried various combinations of that path (e.g. ~/python/myscript.py)
How can I resolve this? I'm running VS for Mac, if that makes a difference.
I want to use syslog-ng to receive netgear log, and use python script process.
But syslog-ng didn't run the python script.
syslog-ng.config
#version:3.2
options {
flush_lines (0);
time_reopen (10);
log_fifo_size (1000);
long_hostnames (off);
use_dns (no);
use_fqdn (no);
create_dirs (no);
keep_hostname (yes);
};
source s_sys {
udp(ip(0.0.0.0) port(514));
};
destination d_python{
program("/usr/local/bin/python /opt/syslog.py");
#program("/bin/echo 'haha' >> /tmp/test");
};
log { source(s_sys); destination(d_python);};
and python script like this
#!/usr/local/bin/python
#coding:utf8
import os
import sys
import datetime
f = open('/var/log/pnet.log', 'a')
f.write('\nstart\n')
f.write('args\n')
f.write('%s\n' % sys.argv)
if not sys.stdin.isatty():
f.write('stdin\n')
f.write('%s\n' % date.date.now().isoformat() )
tty_read = sys.stdin.read()
f.write("'''\n")
f.write(tty_read)
f.write("\n'''\n")
f.write('end\n')
f.close()
The script is already 777
Even I change my config to use 'echo' directly pipe into a file, didn't write a word too...
So...why?
silly question, but do you have incoming logs? If you use a simple file destination instead of the program, do you receive logs? If not, the problem is not in the program destination.
Also, try changing the flush_lines (0); option to 1 to see if it helps.
Regards,
Robert Fekete
I could show you my code for reference:
my syslog-ng.conf :
source s_test{
file("/home/test/in.log" follow-freq(1) flags(no-parse));
};
destination d_test{
program ("/home/test/out.py" flush_lines(1) flags(no_multi_line));
};
log {
source(s_test);
destination(d_test);
flags(flow-control);
};
my out.py:
#!/usr/bin/env python
# encoding: utf-8
import sys
while True:
line = sys.stdin.readline()
file = open("/home/test/out_from_python.log","a")
file.write(line)
file.close()
when you type echo "something" >> /home/test/in.log , there would be a new log lie in /home/test/out_from_python.log