Im trying to read a file using a scanner then have my program print the first line of the file then looping over each other individual line throughout the file and printing them as well. This issue is I cant even get it to print a single line from the first file. And I'm not receiving an error so I cant figure out the issue
import sys
import scanner
def main():
log1 = (sys.argv[1])
log2 = (sys.argv[2])
def readRecords(s):
s = Scanner("log1")
print (log1)
main()
I will go out on a limb here and suggest something like:
import sys
import scanner
def readRecords(log):
s = scanner.Scanner(log)
print s.SomeAttribute
def main():
log1 = (sys.argv[1])
log2 = (sys.argv[2])
readRecords(log1)
readRecords(log2)
main()
Your original code has numerous problems though, least of which you are never calling your readRecords function. You are also never defining/importing Scanner, and you are doing nothing with the s variable that you are assigning to (unless merely creating a Scanner object has the desired side-effect).
Related
I would like a variable to be stored in .py file and be imported into a main Python program.
Let me explain the problem in code. In my home folder I have the following files:
testcode.py
testmodule.py
testcode contains the following code:
import pprint
while __name__ == '__main__':
import testmodule
variableFromFile=testmodule.var
print("Variable from file is "+str(variableFromFile))
print("Enter variable:")
variable=input()
Plik=open('testowymodul.py','w')
Plik.write('var='+variable)
Plik.close()
and testmodule contains:
var=0
Now when I launched testcode.py, and input as variables 1,2,3,4,5 I got the following output:
Variable from file is 0
Enter variable:
1
Variable from file is 0
Enter variable:
2
Variable from file is 0
Enter variable:
3
Variable from file is 0
Enter variable:
4
Variable from file is 0
Enter variable:
5
Variable from file is 0
Enter variable:
But I would like to refresh this variable every time it is printed on screen, so I expect in this line:
print("Variable from file is "+str(variableFromFile))
to update the variable's value. Instead, I get in output only the first value of the variable, so the program print 0 every time. Only restarting the program will refresh the value of var.
Is there a way to import variables from file, change them at runtime and then then use their updated values later on in the script?
I believe your basic problem stems from the use of the variable in the testmodule.py file. As written you code imports this file and thus the pyhton interpreter assigns the value of testmodule.var to the contents thyat exist at load time. The code which attempts to update the variable isn't working the way you intended, since Plik.write('var='+variable) is creating a text string of the form "var = n". Thus subsequent attempts to import the testmodule and get the testmodule.var variable will result in a 0 value.
To fix this problem, as suggested by #JONSG, requires you abandon the import context and do something along the lines of the following:
#Contents of testmodule.txt file
0
#Contents of the testcode.py file
def readVar(fn):
with open(fn, 'r') as f:
return f.read().strip()
def writeVar(fn, val):
with open(fn,'w') as f:
f.write(val)
def runcode():
varfile = 'testmodule.txt' #Assumes testmodule.txt is in same folder as code
variableFromFile= readVar(varfile)
print("Variable from file is "+str(variableFromFile))
variable=input("Enter variable: ")
writeVar(varfile, variable)
def main():
runcode()
if __name__ == "__main__":
main()
Now every time you run the file, the latest variable data will be loaded and then updated with a new value.
I'm creating a similarity program that calculates the euclidean distance of images, I'm looking for user input so that if they want to use a portion of the code, they can choose so. in that case, a line (specifically 13 in dc2.py) needs to be changed to " ". How can i go about this?
I've attempted using the open function alongside .write, opening a file though open(dc.py).read(), and to no avail.
This converts the image into an array (program dc2.py):
import numpy as np
import imageio
from numpy import array
img = imageio.imread("Machine Screw.jpg")
data = array(img)
with open('test2.txt', 'w') as outfile:
np.savetxt(outfile, data_slice, fmt='%-7.2f')
exec(open("Halfer.py").read())
Here's the failed code to change the previous .py:
inp = input("Want to use halfer?: ")
if inp == 'y':
the_file = open('dc2.py', 'a')
the_file[13].write(' ')
--------------------------------------
I expected:
Process finished with exit code 0
here's what actually happened:
Traceback (most recent call last):
File "C:/Users/User/Desktop/PySimCode/Resources/Ini.py", line 5, in <module>
the_file[13].write(' ')
TypeError: '_io.TextIOWrapper' object is not subscriptable
Thank you for all the help!
Your solution what you want to implement is not too "Pythonic". In my opinion you should import dc2.py file as module to Ini.py script and use parameters based on user-input to manipulate the behavior of dc2.py script.
For example:
dc2.py
import numpy as np
import imageio
import subprocess
from numpy import array
def image_converter(halfer_needed=True):
img = imageio.imread("Machine Screw.jpg")
data = array(img)
with open('test2.txt', 'w') as outfile:
np.savetxt(outfile, data, fmt='%-7.2f')
if halfer_needed:
sp = subprocess.Popen(["python", "Halfer.py"]) # Call Halfer.py script
ret_stdout, ret_stderr = sp.communicate() # These variables contain the STDOUT and STDERR
ret_retcode = sp.returncode # This variable conains the return code of your command
I think you want to call the Halfer.py script if user wants it so I have used the subprocess module to call this script as you can see above. You can see more details and options about this module: https://docs.python.org/3/library/subprocess.html
Ini.py
from dc2 import image_converter # Import your function from "dc2.py" script
inp = str(input("Want to use halfer?: "))
if inp == 'y':
image_converter(halfer_needed=False)
image_converter() # you don't need to define the keyword argument because the default value is True.
Try this:
inp = raw_input("Want to use halfer?: ")
if inp == 'y':
origin_file = open('dc2.py','r').readlines()
the_file = open('dc2.py','w')
origin_file[12] = '\n'
for line in origin_file:
the_file.write(line)
the_file.close()
Some notes I'd like to add:
input reads a block of text and parses it. You should probably always use raw_input.
open does different things, depending on the mode parameter. In my case, I used r for reading, then w for writing. (I don't think there's a way to read and write on the same <open> object). a is append, which only lets you add lines. Read here
To get the contents from an <open>, use .read() or .readlines().
The 13th line is index 12. Also, I changed it to '\n' instead of ' '.
Don't forget to call .close() on your <open> when you are done with it!
Hope this works for you!
You can, but you shouldn't.
You are trying to activate some code based on uer imput, this is doable encapsulating the code in functions, that you can import and axecute based on a condition.
You are trying to achieve this result by reading files and executing them manually, basically you are doing what the Python interpreter should do..
First, you need to chage you modules to something that activates at will, not as soon as the file is loaded, for instance your dc2.py would look like this:
import numpy as np
import imageio
from numpy import array
import Halfer # <- here you import the py file, not open and read
def run(use_halfer):
img = imageio.imread("Machine Screw.jpg")
data = array(img)
with open('test2.txt', 'w') as outfile:
np.savetxt(outfile, data_slice, fmt='%-7.2f')
if use_halfer:
Halfer.run()
..and your Halfer.py file should look like this:
def run():
# ..all your Halfer.py code here inside the run function
..and then your starting point of the script can look like:
import dc2
inp = input("Want to use halfer?: ")
dc2.run(inp == 'y') # <- here you tell dc2 to use halfer or not.
I have a program, like:
module "Main":
import SymbolCalculator as sc
# Defining constants:
TEXT_INTRO = sc.TEXT_INTRO
TEXT_INVITE = "Please print any sentence below:\n"
sentence = ""
# Printing introduction to the program:
print TEXT_INTRO
def getting_result():
# Getting input string from console
sentence = sc.get_input_from_prompt(TEXT_INVITE)
# Forming result list via methods defined in SymbolCalculator module
return sc.characters_calculator(sentence)
result_list = getting_result()
# Computing summary via method defined in SymbolCalculator module
sc.printing_summary(sentence, result_list)
# Printing tuples with characters and their occurrences raw-by-raw
sc.printing_list(result_list)
raw_input("Please press any button to quit the program.")
print 'Bye!!!'
And I'm trying to create a simple unit test with mocked raw_input (updated):
from unittest import TestCase, main
from mock import patch
from Ex_41_42_SymbolCalculatorMain import getting_result
class Ex_4a1_SymbolCalculatorUnitTestWMock(TestCase):
##patch ('Ex_41_42_SymbolCalculator.get_input_from_prompt', return_value = 'aabc')
def test_valid_input(self):
with patch('__builtin__.raw_input', return_value = 'aaabbc') as _raw_input:
self.assertEqual(getting_result(), [('a', 3), ('b', 2), ('c', 1)])
_raw_input.assert_called_once_with('Please print any sentence below:\n')
#patch ('Ex_41_42_SymbolCalculator.get_input_from_prompt', return_value = '')
def test_empty_input(self, mock):
self.assertEqual(getting_result(), [])
if __name__ == "__main__":
main()
As well I tried to go via decoration of the tested method by itself, like:
...
#patch ('Ex_41_42_SymbolCalculator.get_input_from_prompt', return_value = 'aabc')
...
My problem is that when I launch the test, all the "Main" module runs at the moment of getting_result method calling. So it starts from the very beginning, asks me to make an input via command prompt, etc. Thus not only test, but the whole regular program is running.
While I'm expecting that only getting_result method is called being provided with return_value.
Please advise.
When you import a module, all the code in the module is run. It doesn't matter that you used from Ex_41_42_SymbolCalculatorMain import getting_result instead of import Ex_41_42_SymbolCalculatorMain; you're still importing the module. There's no way to just "get" one function without executing the rest of the code in the module.
Instead, you should put that code in a function, and then call it from within an if __name__ == "__main__" block, like this:
def getting_result():
# Getting input string from console
sentence = sc.get_input_from_prompt(TEXT_INVITE)
# Forming result list via methods defined in SymbolCalculator module
return sc.characters_calculator(sentence)
def do_stuff():
print TEXT_INTRO
result_list = getting_result()
# Computing summary via method defined in SymbolCalculator module
sc.printing_summary(sentence, result_list)
# Printing tuples with characters and their occurrences raw-by-raw
sc.printing_list(result_list)
raw_input("Please press any button to quit the program.")
print 'Bye!!!'
if __name__ == "__main__":
do_stuff()
Then do_stuff() will only be run if you execute that file directly, not if you import it. This will allow you to import the module without running the stuff in do_stuff. You can learn more about the __main__ business by searching this site for zillions of questions about it (such as this one).
I'm currently setting up a some sensors with my raspberry pi in python. Total python newbie here.
Each sensor has it's own script to read the sensor and there is another script that drives an LCD display and displays the imported variable from the sensor script.
I've gotten so far with working scripts that run the sensors and generate output, however, I cannot seem to import the variables (temperature & pH) into the LCD display script. Also, once I have imported the variables, how do I instruct the LCD script to "refresh" the and fetch the updated variable?
Here's a trimmed down version of what I have so far, I've omitted the sensor and data logging parts of each script. For simplicity, script_display is the LCD driver, and pH_script is for pH and temp_script is for temperature.
Here's a simplified version of the scripts:
script_display.py
import sys
sys.path.insert(0, '/home/pi/Raspberry-Pi-sample-code')
import pH_script
import temp_script
from ph_script import ph_main
from temp_script import get_temp
import time
while True:
print PH.ph_main(ph_output)
print get_temp(temp)
time.sleep(1)
temp_script.py
from w1thermsensor import W1ThermSensor
import time
#Get Temperature
def get_temp():
global temp
sensor = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "031683a0a4ff")
activate_temp = sensor.get_temperature()
temp = str(activate_temp)
return temp
#Read Temp Frequency
def read():
threading.Timer(0.5, read).start()
get_temp()
time.sleep(1)
try:
while True:
read()
get_temp()
print get_temp()
except KeyboardInterrupt:
print("Program Ended By User")
pH_script.py
def ph_main():
lots and lots of code to activate the PH probe, and other variables, but the variable ph_output returns as a string, ph_output
try:
while True:
global ph_output
dev.send_cmd("R")
lines = dev.read_lines()
for i in range(len(lines)):
print lines[i]
if lines[i][0] != '*':
print lines[i]
ph_output = str(lines[i])
return ph_output
time.sleep(delaytime)
try:
while True:
ph_main()
except KeyboardInterrupt:
print("Continuous polling stopped")
so, again, first question, how to pass the global variables back to the display script? and two, how to instruct the display script to 'refresh' the variables?
the error I am currently getting is:
Traceback (most recent call last):
File "script_display.py", line 8, in <module>
print PH.ph_main(ph_output)
NameError: name 'ph_output' is not defined
looking forward to any input and thanks for your time + help!
I'm trying to write a python script to read values from the arduino's serial port and write it to a file so I can log the data.
The arduino code is long and complicated, but I'm using Serial.println() to print an integer to the serial port (located at /dev/ttyACM0)
import sys
import serial
import getpass
import datetime
import instrumentDriver
"""location of the arduino"""
location = '/dev/ttyACM0'
"""Connect to the arduino"""
arduino = instrumentDriver.serialDevice(location)
"""Successfully connected!"""
filename = str(sys.argv[1])
dataFile = open(filename+'.dat','w')
"""The main loop -- data is taken here and written to file"""
while True:
try:
datum = arduino.read()
print datum
dataFile.write(datetime.datetime.now().strftime("%Y-%m-%d"))
dataFile.write('\t')
dataFile.write(datum)
dataFile.write('\n')
except:
dataFile.close()
break
The instrumentDriver.py is just a wrapper for pySerial:
class serialDevice:
def __init__(self,location):
self.device = location
self.port = serial.Serial(location,9600)
def write(self,command):
self.port.write(command)
def read(self):
return self.port.readline()
I've used this block of code years ago and it worked fine, but it seems to be failing right now and I'm not entirely sure why. I get a SyntaxError on line 45:
scottnla#computer-1 ~/Documents/sensorTest $ python readSerial.py file
File "readSerial.py", line 45
print datum
^
SyntaxError: invalid syntax
I've tried changing the print statement, but no matter what I'm printing, I get a syntax error -- I speculate that the problem may actually be with the arduino.read() line.
Any advice would be greatly appreciated!
There is still an indentation issue; rewritten as below, it should run:
import sys
import datetime
class serialDevice:
def __init__(self,location):
self.device = location
self.port = sys.stdin # changed to run on terminal
def write(self,command):
self.port.write(command)
def read(self):
return self.port.readline()
"""location of the arduino"""
location = '/dev/ttyACM0'
"""Connect to the arduino"""
arduino = serialDevice(location)
"""Successfully connected!"""
filename = str(sys.argv[1])
dataFile = open(filename+'.dat','w')
"""The main loop -- data is taken here and written to file"""
while True:
try:
"""retrieve the raw analog number from the arduino's ADC"""
datum = arduino.read()
"""write it to file, along with a timestamp"""
print datum
dataFile.write(datetime.datetime.now().strftime("%Y-%m-%d"))
dataFile.write('\t')
dataFile.write(datum)
dataFile.write('\n')
except KeyboardInterrupt:
"""this allows for the user to CTRL-C out of the loop, and closes/saves the file we're writing to."""
dataFile.close()
break