I have a 'working' Python code, TCP_Barcode_V1.py which read a text file and gives output in a tkinter window.
However, if I convert the Python file to an .exe using auto-py-to-exe, when executing TCP_Barcode_V1.exe, am getting error like fatal error occurred Failed to execute script TCP_Barcode_V1 in a messagebox
my text file, param.txt looks like this :
192.1.22.43
6666
3000
each line is read and stored in a variable
In my python file, am reading the file as
THIS_FOLDER = os.path.dirname(os.path.abspath(__file__))
my_file = os.path.join(THIS_FOLDER, 'param.txt')
with open(my_file, "r") as fp:
val = [line.strip() for line in fp]
duration = int(val[0])
TCP_IP = val[1]
TCP_PORT = int(val[2])
Can someone identify what the problem here is.
Please note that the original TCP_Barcode_V1.py is working without any issues. And also, I am using the same device for running the .py as well as .exe file.
below is my auto-py-to-exe settings I chose
Related
import os ,fnmatch
import os.path
import os
file_dir= '/home/deeghayu/Desktop/mec_sim/up_folder'
file_type = ['*.py']
for root, dirs,files in os.walk( file_dir ):
for extension in ( tuple(file_type) ):
for filename in fnmatch.filter(files, extension):
filepath = os.path.join(root, filename)
if os.path.isfile( filepath ):
print(filename , 'executing...');
exec(open('/home/deeghayu/Desktop/mec_sim/up_folder/{}'.format(filename)).read())
else:
print('Execution failure!!!')
Hello everyone I am working on this code which execute a python file using a python code. I need to save my output of the code as a text file. Here I have shown my code. Can any one give me a solution how do I save my output into a text file?
Piggybacking off of the original answer since they are close but it isn't a best practice to open and close files that way.
It's better to use a context manager instead of saying f = open() since the context manager will handle closing the resource for you regardless of whether your code succeeds or not.
You use it like,
with open("file.txt","w+") as f:
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
try
Open file
f= open("file.txt","w+")
Insert data into file
for i in range(10):
f.write("This is line %d\r\n" % (i+1))
Close the file
f.close()
I'm new in python, I have written a python program that reads a list of files and saves the total number of a particular character (ch) in a dictionary and then returns it.
The program works fine, now I'm trying to write a simple test code to test the program.
I tried with the following code,
def test_read_files():
assert read_files("H:\\SomeTextFiles\\zero-k.txt", 'k') == 0, "Should be 0"
if __name__ == "__main__":
test_read_files()
print("Everything passed")
I named the program as test_read_files.py
My python code is as follows:
# This function reads a list of files and saves number of
# a particular character (ch) in dictionary and returns it.
def read_files(filePaths, ch):
# dictionary for saing no of character's in each file
dictionary = {}
for filePath in filePaths:
try:
# using "with statement" with open() function
with open(filePath, "r") as file_object:
# read file content
fileContent = file_object.read()
dictionary[filePath] = fileContent.count(ch)
except Exception:
# handling exception
print('An Error with opening the file '+filePath)
dictionary[filePath] = -1
return dictionary
fileLists = ["H:\\SomeTextFiles\\16.txt", "H:\\SomeTextFiles\\Statement1.txt",
"H:\\SomeTextFiles\\zero-k.txt", "H:\\SomeTextFiles"]
print(read_files(fileLists, 'k'))
I named it as read_files.py
When I run the test code, getting an error: NameError: name 'read_files' is not defined
The program and the test code all are in the same folder (different than the python folder though).
Hopefully I am understanding this correctly, but if both of you python files:
test_read_files.py
read_files.py
Are in the same directory.. Then you should be able to just add at the top of the test_read_files.py the following import command:
from read_files import read_files
This will import the read_files function from your read_files.py script and that way you will be able to run it inside the other file.
I'm working on building a script for configuring disks automatically on linux systems. One of my functions is not working and for the life of me I cannot figure out why.
I've tested the code on pythontutor.com with no errors. When I run the code on my machine, I get no errors, but instead of the function returning data from the file "disks.txt" I get empty dictionaries.
I have tried to add print statements at different points in the process to see what is going on, but nothing prints.
Here is my function:
def check_for_disks():
cmd = 'lsblk -l -o name,mountpoint'.split()
driveDict = {}
finalDict = {}
diskFile = open("disks.txt", "w+")
subprocess.Popen(cmd, stdout=diskFile)
diskFile.close()
diskFile = open("disks.txt", "r+")
for line in diskFile.readlines():
dictItem = line.split()
try:
driveDict[dictItem[0]] = dictItem[1]
except(IndexError):
driveDict[dictItem[0]] = "No MountPoint Defined"
diskFile.close()
for k, v in driveDict.items():
if 'sd' in k:
finalDict[k] = v
else:
pass
return finalDict
This part works flawlessly and creates the file I want, with the relevant information:
def check_for_disks():
cmd = 'lsblk -l -o name,mountpoint'.split()
driveDict = {}
finalDict = {}
diskFile = open("disks.txt", "w+")
subprocess.Popen(cmd, stdout=diskFile)
diskFile.close()
This part fails:
diskFile = open("disks.txt", "r+")
for line in diskFile.readlines():
It is seemingly just not opening the file. I've checked the file with ls -la and seen its permissions are fine aka -rw-rw-r--
I've tried with open("disks.txt", "a+") as diskFile:
I've tried the options "r", "r+", "a+"
I've run the script sudo
Any help is appreciated
PLEASE SAVE ME I'M GOING NUTS
TLDR: the file is empty when you open it.
The following command opens a new thread, and the new thread, starts to write this file.
subprocess.Popen(cmd, stdout=diskFile)
But at the same time, as the file is begin created you start to read the file. Two threads makes this command faster, but I don't think you need that. Simply, wait until the file is finished before reading it.
something like this, should do what you want
p = subprocess.Popen(cmd, stdout=diskFile)
p_status = p.wait() #finish writing the file before starting to read it
Let me know if you really need to multiple threads, or if this snippet has any issues.
I am trying to send a XML file to RabbitMQ from python but I am getting the below error
Error
File "<ipython-input-134-8a1b7f8b2e41>", line 3
channel.basic_publish(exchange='',queue='abc',''.join(lines))
^
SyntaxError: positional argument follows keyword argument
My Code
import ssl
!pip install pika
import pika
ssl_options = pika.SSLOptions(ssl._create_unverified_context())
credentials = pika.PlainCredentials(username='abcc', password='abcc')
connection = pika.BlockingConnection(pika.ConnectionParameters(
host='xxxx', port=5671, virtual_host ='xxx', credentials=credentials,
ssl_options=ssl_options))
channel = connection.channel()
result = channel.queue_declare(queue='abc')
with open('20200205280673.xml', 'r') as fp:
lines = fp.readlines()
channel.basic_publish(exchange='',queue='abc',''.join(lines))
Whats wrong in the above code?
As #ymz suggested, you are missing the body key in the basic.publish method. Also, the basic_publish method has no argument called queue. Please have a look at its implementation docs
Edit #1: I have already answered this question elsewhere How to send a XML file to RabbitMQ using Python?
Edit #2: Automating publishing of XML files. Assuming all the files are present in a directory called xml_files
import os
DIR = '/path/to/xml_files'
for filename in os.listdir(DIR):
filepath = f"{DIR}/{filename}"
with open(filepath) as fp:
lines = fp.readlines()
channel.basic_publish(exchange='exchange', routing_key='queue', body=''.join(lines))
I'm trying to write a script in which I need to get the terminal size in order to adjust the output text width appropriately. I use this lines:
import os
x = os.get_terminal_size().lines
which results in getting this error:
ValueError: bad file descriptor
What's wrong with the code?
Try this:
import sys
import os
try:
cols,rows = os.get_terminal_size(0)
except OSError:
cols,rows = os.get_terminal_size(1)
sys.stdout.write('cols:{} \n rows:{} \n'.format(cols,rows))
Check out this page you can find multiple example with error handling