How to continue writing to string in python - python

In python I have written something like this;
script = """
import network
from machine import Pin, PWM
from time import sleep
"""
And I want to write something after it but without deleting the old ones. How do I do?

You can append a string to a string like following
>>> script = """
... import network
... from machine import Pin, PWM
... from time import sleep
... """
>>> script += "\nimport os"

You could put the script into a template and then fill in the values. This might be easier to manage than concatenating strings if your generated script is even moderately complex.
# script.template
import network
from machine import Pin, PWM
from time import sleep
${xyz}
# script-generator.py
from string import Template
with open('script.template') as f:
template = Template(f.read()
contents = template.substitute(xyz='xyz')
with open('main.py', 'w') as f:
f.write(contents)
Or you could use str.format() like this if a separate template file seems like overkill:
script = """\
import network
from machine import Pin, PWM
from time import sleep
{xyz}
"""
data = {'xyz': 'xyz'}
with open('main.py', 'w') as f:
f.write(script.format(**data))

Related

Trying to import a script from other code

I need help to import a script, i did 2 codes, the first is a test with some prints and in the second i try to import them:
Code 1
# I make some print's to try import and show if it works
def first():
print('Test')
class phrase:
def second():
print('Hello')
def third():
print('World')
Code 2
import os
attempt = os.system(r"python C:\Users\Gabri\PycharmProjects\pythonProject\Imagens.py")
# Obviously isn't works =(
attempt.first()
But in code 2, when i did os.system(r"python C:\Users\Gabri\PycharmProjects\pythonProject\Imagens.py") nothing happen.
Someone can help me to import this code? ;-;
1° Code is in C:\Users\Gabri\PycharmProjects\pythonProject
2° in C:\Users\Gabri\PycharmProjects\pythonProject\Prática\Vamove
If you want to keep the files where they are,
You should by able to do this:
import importlib.util
spec = importlib.util.spec_from_file_location(
"name", "C:\\Users\\Gabri\\PycharmProjects\\pythonProject\\Imagens.py")
Imagens = importlib.util.module_from_spec(spec)
spec.loader.exec_module(Imagens)
And then run your commands like this:
Imagens.first()
The easiest is if you put both in the same folder and make that folder a python directory from which you can import your other code as modules. All you need for that is a file in the folder containing a blank __init__.py file. Then you can import it to another code file in the same folder using
from folder_name import Imagens
and you should be able to use Imagens functions like any other module
Ex: Imagens.first()

pm4py Error: cannot import name 'factory' from 'pm4py.algo.discovery.alpha'

I am trying to run the following code:
from pm4py.algo.discovery.alpha import factorial as alpha_miner
from pm4py.objects.log.importer.xes import factory as xes_importer
event_log = xes_importer.import_log(os.path.join("tests","input_data","running-example.xes"))
net, initial_marking, final_marking = alpha_miner.apply(event_log)
gviz = pn_vis_factory.apply(net, initial_marking, final_marking)
pn_vis_factory.view(gviz)
However, when I run the alpha miner, I get an error message that factory cannot be imported.
What could be the reason or does anyone know a soulution for this?
Many thanks for the answer
from pm4py.algo.discovery.alpha import algorithm as alpha_miner
Find all process discoveries and its information at:
https://pm4py.fit.fraunhofer.de/documentation#discovery
Try this:
import os
# Alpha Miner
from pm4py.algo.discovery.alpha import algorithm as alpha_miner
# XES Reader
from pm4py.objects.log.importer.xes import importer as xes_importer
# Visualize
from pm4py.visualization.petri_net import visualizer as pn_visualizer
log = xes_importer.apply(os.path.join("tests","input_data","running-example.xes"))
net, initial_marking, final_marking = alpha_miner.apply(log)
gviz = pn_visualizer.apply(net, initial_marking, final_marking)
pn_visualizer.view(gviz)

How to get data just from one channel using python and alsaaudio

I am using python 3 and with alsaaudio I read data from microphone but I have to work with each channel separately. So is there a way how to get data just from one channel? Or how to parse data from each channel separately?
import wave
import sys
import threading
import time
import os
import alsaaudio, audioop
# Input
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)
inp.setchannels(2)
inp.setrate(8000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
inp.setperiodsize(80)
# Output file
output = wave.open("test2.wav",'wb')
output.setnchannels(2)
output.setsampwidth(2)
output.setframerate(8000)
while True:
l,frames = inp.read()
if l>0:
print(frames)
output.writeframes(frames)

Python 3 script crash on lru_cache

I have raspberry pi acting as MFRC522 card reader. So far I have a script which worked on python 2.7, but when I tried to move to python 3, bizarre thing happened.
I used updated library for it: https://github.com/pimylifeup/MFRC522-python and adjusted my script accordingly
I installed pip3 and spidev
Here is where strange thing happens. If I run demo script from repo above in new folder it works, cool.
But if I put my previous script in the same folder it returns error as below. And after that if I try again to run demo script, same error occurs.
Moving both script to different folder, has the same effect. I can run demo only before my script. Doing that after, is impossible.
Error:
File "/usr/lib/python3.7/re.py", line 297, in <module>
#functools.lru_cache(_MAXCACHE)
AttributeError: module 'functools' has no attribute 'lru_cache'
My script:
import RPi.GPIO as GPIO
from mfrc522 import SimpleMFRC522
import time
import requests
import signal
import sys
import os
# some functions non related to MFRC522
reader = SimpleMFRC522()
while continue_reading:
try:
id, text = reader.read()
#print id
#print "---"
ver = query_server(id)
if ver == 1:
open_relay(5)
else:
#do something
finally:
time.sleep(0.5)
It's like folder is somehow tainted after firing my script, what am I missing?

How do you set the results_directory in SST Python

I'm feeling a bit foolish asking this, as with basic selenium I have no problem saving screenshots, yet with SST I use the take_screenshot('screenshot_name.png') it tells me that the results_directory should be set. Question is how do you set the results_directory. All of the examples I find set it to "NONE", yet that doesn't satisfy my test's need.
Below is how my code is written:
import unittest
from sst.actions import *
from sst import cases, config
config.results_directory = None
class TestMyTest(cases.SSTTestCase):
def test_mytestcase_home_page(self):
go_to('http://www.mywebpage.com')
assert_title_contains('MyWebPage')
#Main page is displayed
take_screenshot(filename='C/Users/Brenda/test/SST Test Project/results/home_page.png',add_timestamp=True)
I had the following script working for me using Google. The trick was to add result directory to actual config file which is located #{dir}\Python27\Lib\site-packages\sst\config.py and add results_directory = "C:\Users\{me}\Desktop\Python-pip-SST\results"
import unittest
from sst.actions import *
from sst import cases, config
#config.results_directory = "C:\Users\{me}\Desktop\Python-pip-SST\results"
go_to('https://www.google.com/')
assert_title_contains('Google')
#Main page is displayed
take_screenshot(filename='home_page.png',add_timestamp=True)
And, You also should be able to overwrite the result path from your test. Your working code should look like something like the following
import unittest
from sst.actions import *
from sst import cases, config
#Just to be safe side try not to use any spaces in filename
config.results_directory = "C:/Users/Brenda/test/SSTTestProject/results"
class TestMyTest(cases.SSTTestCase):
def test_mytestcase_home_page(self):
go_to('http://www.mywebpage.com')
assert_title_contains('MyWebPage')
#Main page is displayed
take_screenshot(filename="home_page.png",add_timestamp=True)
I added the screenshot if that helps you somehow. Changing filepath innconfig file or from test works fine for me

Categories

Resources