Expected Behavior
Automatically run a program to record a video for a short length of time.
Save the video to a unique filename within a specific directory (to avoid overwriting). Ideally, this filename would include the date and time.
Actual Behavior
Success
Filename is always video.h264.
I have tried all sorts of things that I have found on the net, but they only result in the file name showing part of the code. Annoyingly it worked once, but saved it to somewhere I was not expecting and I changed the code before I realized it had worked!
Full File
# Import Libraries
import os #Gives Python access to Linux commands
import time #Proves time related commands
import RPi.GPIO as GPIO #Gives Python access to the GPIO pins
GPIO.setmode(GPIO.BCM) #Set the GPIO pin naming mode
GPIO.setwarnings(False) #Supress warnings
# Set GPIO pins 18 as output pin
LEDReady = 18 #Red
GPIO.setup(LEDReady,GPIO.OUT)
GPIO.output (LEDReady,GPIO.HIGH)
from subprocess import call
call(["raspivid", "-o", "video.h264", "-t", "50000n"])
time.sleep(10) #Sleep for 10 seconds
GPIO.output (LEDReady,GPIO.LOW)
Adding DATE=$(date +"%Y-%m-%d_%H%M")
and changing video.h264 to $DATE.h264 results in a syntax error for $DATE.
Tantalizingly, I have a file called 20180308_021941.h264 which is exactly what I am after, but I cannot tell you how I managed it!
P.S. the Red LED lighting up is so that I can tell if the Raspberry Pi has fired up properly and has run the Python script.
Thank you for taking the trouble to read this.
Try adding this
from datetime import datetime
date = datetime.now().strftime("%Y%m%d%H:%M:%S")
Then change your call to this
videoFile = date + ".h264"
call(["raspivid", "-o", videoFile, "-t", "50000n"])
Related
So I am using a raspberry pi system and am trying to write code in the python to have the system read the humidity and temperature. We are able to get the humidity sensor to read the humidity and temperature in terminal, so we are somewhat sure we set it up right. When we try to import Adafruit_DHT into python (out written code) we get an error when we run the code. Any help would be greatly appreciated!
Here is more info about the code:
Terminal entry:
pi#raspberrypi:~/Adafruit_Python_DHT/examples $ python AdafruitDHT.py 22 4
Temp=24.1* Humidity=48.4%
Python Code:
import Adafruit_DHT
#set sensore type : options are DHT11, DHT22
sensor=Adafruit_DHT.DHT22
#white is 22
#set GPIO sensor is connected to
gpio=4
#use read_retry method, this will retry up to 15 times to get
#a sensor reading (waiting two seconds between each try
humidity, temperature = Adafruit_DHT.read_retry(sensor, gpio)
#reading the DHT11 is very sensitive to timings and sometimes the Pi might
#fail to get a valid reading (so check)
if humidity is not None and temperature is not None:
print('Temp={0:0.1f}*C Humidity={1:0.1f}%'.format(temperature, humidity))
else:
print('Failed to get reading. Try again!')
Error from running:
Traceback (most recent call last):
** IDLE Internal Exception:
File "/usr/lib/python3.4/idlelib/run.py", line 353, in runcode
exec(code, self.locals)
File "/home/pi/hopeful dht run.py", line 1, in <module>
import Adafruit_DHT
ImportError: No module named 'Adafruit_DHT'
Thank you so much!
Izzy
You haven't installed the adafruit_dht library. Need to:
Enter the following in your terminal to install the Adafruit Python DHT Library:
sudo pip3 install Adafruit_DHT
https://learn.adafruit.com/adafruit-io-basics-temperature-and-humidity/python-setup
https://www.raspberrypi.org/forums/viewtopic.php?t=235179
***if you have done this, and getting the same error, try running python, python2, or python3. You might not have everything updated.
My python script passes changing inputs to a program called "Dymola", which in turn performs a simulation to generate outputs. Those outputs are stored as numpy arrays "out1.npy".
for i in range(0,100):
#code to initiate simulation
print(startValues, 'ParameterSet:', ParameterSet,'time:', stoptime)
np.save('out1.npy', output_data)
Unfortunately, Dymola crashes very often, which makes it necessary to rerun the loop from the time displayed in the console when it has crashed (e.g.: 50) and increase the number of the output file by 1. Otherwise the data from the first set would be overwritten.
for i in range(50,100):
#code to initiate simulation
print(startValues, 'ParameterSet:', ParameterSet,'time:', stoptime)
np.save('out2.npy', output_data)
Is there any way to read out the 'stoptime' value (e.g. 50) out of the console after Dymola has crashed?
I'm assuming dymola is a third-party entity that you cannot change.
One possibility is to use the subprocess module to start dymola and read its output from your program, either line-by-line as it runs, or all after the created process exits. You also have access to dymola's exit status.
If it's a Windows-y thing that doesn't do stream output but manipulates a window GUI-style, and if it doesn't generate a useful exit status code, your best bet might be to look at what files it has created while or after it has gone. sorted( glob.glob("somepath/*.out")) may be useful?
I assume you're using the dymola interface to simulate your model. If so, why don't you use the return value of the dymola.simulate() function and check for errors.
E.g.:
crash_counter = 1
from dymola.dymola_interface import DymolaInterface
dymola = DymolaInterface()
for i in range(0,100):
res = dymola.simulate("myModel")
if not res:
crash_counter += 1
print(startValues, 'ParameterSet:', ParameterSet,'time:', stoptime)
np.save('out%d.npy'%crash_counter, output_data)
As it is sometimes difficult to install the DymolaInterface on your machine, here is a useful link.
Taken from there:
The Dymola Python Interface comes in the form of a few modules at \Dymola 2018\Modelica\Library\python_interface. The modules are bundled within the dymola.egg file.
To install:
The recommended way to use the package is to append the \Dymola 2018\Modelica\Library\python_interface\dymola.egg file to your PYTHONPATH environment variable. You can do so from the Windows command line via set PYTHONPATH=%PYTHONPATH%;D:\Program Files (x86)\Dymola 2018\Modelica\Library\python_interface\dymola.egg.
If this does not work, append the following code before instantiating the interface:
import os
import sys
sys.path.insert(0, os.path.join('PATHTODYMOLA',
'Modelica',
'Library',
'python_interface',
'dymola.egg'))
I am about to adjust the music fiddler add-on for ANKI SRS for windows users.
Anki ONLY runs add-ons with with ending .py, not pyw. Is there any way to hide the console that automatically pops up when I run the code.
If not, is there a way no to unselect the console windows (i basically have to click on the main anki windows after every five seconds because the console that as already closed again was in selection).
The command I use so far for opening windows is for example:
os.system('"nircmd.exe changesysvolume"'+ change)
The complete code is below
The console runs the nircmd.exe and the number of volume units the system sound should change.
Is there a possibility to adjust the code?
# -*- coding: utf-8 -*-
# Music-Fiddler (a plugin for Anki)
# coded by D_Malik, malik6174#gmail.com
# Version 1
# License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html
"""
A simple plugin that fiddles with music volume to reinforce quick reviewing.
Before using:
- This plugin was made for Linux. It will require modification to work on another OS.
- Ensure that the "amixer" command works on your computer. If it doesn't, you're going to need to modify the code somehow. Don't ask me how.//Amixer has been replaced by nircmd.exe for windows
- Change all lines (in the plugin source) marked with "CHANGEME" according to your preferences.
"""
import os
from aqt import mw
from aqt.utils import showInfo
from os import system
from aqt.qt import *
from anki.hooks import addHook
def resetMusicTimer():
"Boosts volume back up and starts the music timer."
#CHANGEME: The next lines are a python dictionary associating deck names with times (in milliseconds) between volume-decrements.
#Eg, when using the deck "brainscience", volume will decrement every 5 seconds. When using a deck without a listed name, "other" is used.
#Change this according to your decks. Decks with shorter, easier cards need less time.
deckMusicTimes = {
"rocketsurgery" : 3000,
"brainscience" : 5000,
"other" : 5000,
}
if mw.col.decks.current()['name'] in deckMusicTimes:
mw.musicTimeToDecrement = deckMusicTimes[mw.col.decks.current()['name']]
else:
mw.musicTimeToDecrement = deckMusicTimes["other"]
boostMusicVolume()
mw.musicTimer = QTimer(mw)
mw.musicTimer.setSingleShot(True)
mw.musicTimer.start(mw.musicTimeToDecrement)
mw.connect(mw.musicTimer, SIGNAL("timeout()"), decrementMusicVolume)
#showInfo(mw.state)
def changeMusicVolume(change):
"Changes volume according to string; can be either absolute ('40') or change ('2%-')."
os.system('"nircmd.exe changesysvolume"'+ change) #CHANGEME somehow, if amixer doesn't work
def boostMusicVolume():
#showInfo("boosted") #To test changes, you can uncomment this line.
os.system('"nircmd.exe changesysvolume 50000"') #CHANGEME somehow, if amixer doesn't work
#CHANGEME: Set to however high you want your volume to go each time it's boosted back.
#Protip: your music-playing program might have its own "volume multiplier" that you can adjust easily.
def killMusicVolume():
#showInfo("killed") #To test changes, you can uncomment this line.
os.system('"nircmd.exe mutesysvolume 1"') #CHANGEME somehow, if amixer doesn't work
#CHANGEME: Set to how low volume should go when it dies, eg due to undoing a card.
def decrementMusicVolume():
"When reviewing, decrements volume, then sets a timer to call itself. When not reviewing, kills volume and stops timer."
if mw.state == "review":
#showInfo("music volume goes down") #To test changes, you can uncomment this line.
os.system('"nircmd.exe changesysvolume -5000"') #CHANGEME somehow, if amixer doesn't work
mw.musicTimer.start(mw.musicTimeToDecrement) #(start the timer again)
else:
killMusicVolume()
mw.musicTimer = None #(kill the timer if you're not reviewing)
addHook("showQuestion", resetMusicTimer)
It seems using the subprocess module instead of os.system will solve your problem. Please see How to avoid console window with .pyw file containing os.system call? and How do I hide the console when I use os.system() or subprocess.call()?.
I am trying to draw a protein structure from a pdb file using pymol.
However, when I try to run the script below, a pymol window opens but it is just pitch black. Also, bizarrely, the pdb file is outputted to the shell.
Here is my code:
bioservices_pdb_obj = PDB()
pdb_file = bioservices_pdb_obj.getFile(results[str(Brick.part_attrib(self,'uniprot_id'))][detail-1],'pdb')
pdb_name = str(Brick.part_attrib(self,'uniprot_id'))
pymol.finish_launching()
pymol.cmd.load(pdb_file, pdb_name)
pymol.cmd.disable("all")
pymol.cmd.enable(pdb_name)
pymol.cmd.png("my_pdb.png")
pymol.cmd.quit()
Does anyone know what is going on here?
The .png file 'my_pdb' is dumped into the working directory, but that's just black as well.
Does this also happen with any other PDB file? If yes, you can try a workaround using the cmd.mpng() function. You can use this function also in other contexts if the cmd.png() function doesn't work, e.g. when using PyMOL in command-line mode.
import pymol
from pymol import cmd
import os
pymol.finish_launching()
cmd.set('ray_trace_frames', 1) # Frames are raytraced before saving an image.
def pnghack(filepath, width=1024, height=768):
"""Workaround if cmd.png() doesn't work"""
cmd.viewport(width, height) # Set resolution
cmd.mpng(filepath, 1, 1) # Use batch png mode with 1 frame only
cmd.mplay() # cmd.mpng needs the animation to 'run'
cmd.load(pdb_file, pdb_name)
cmd.disable("all")
cmd.enable(pdb_name)
pnghack("my_pdb.png")
cmd.quit()
Note that the resulting png file is named "my_pdb0001.png" as the cmd.mpng() function always adds the framenumber.
I am trying to make a python program that writes the follwing to a terminal:
Frame 1 -- Loading
Frame 2 -- Loading.
Frame 3 -- Loading..
Frame 4 -- Loading...
Frame 5 -- Loading
This would all be a function so that it repeats itself. The one problem I am having is that I have no idea how to reset the number of dots to zero after they equal three. My current code is below, any suggestions would be nice.
import pickle
import time
from sys import stdout
stdout.write("Loading")
def loaddot():
stdout.write(".")
time.sleep(.5)
loaddot()
loaddot()
Here is my attempt:
import time
from sys import stdout
def loaddot():
stdout.write("."*(dots%3 + 1))
time.sleep(.5)
dots = 0
while(True):
dots += 1
stdout.write("Loading")
loaddot()
stdout.flush()
print
I believe there are better ways to do it in Python. I have not worked with the language that much, but this comes from what I know and my background in other languages.
To do something like this, you really should be using the curses library. There exist several hacks to get the screen to clear, or backspace characters, but none compare to the UI features of curses:
http://docs.python.org/2.7/library/curses.html
You need to clear the screen, if you are on a linux system simply use the os library
import os
import time
while True:
for i in range(3):
print "Loading."<br>
time.sleep(3)<br>
os.system("clear")<br>
print "Loading.."<br>
time.sleep(3)<br>
os.system("clear")<br>
print "Loading..."<br>
time.sleep(3)<br>
os.system("clear")<br>