I expect the program to open the link specified and then close the browser after some time.REPEAT this task 3 times.
But I end up getting the mentioned error.
import time
import subprocess
total_breaks = 3
break_count = 0
print("This program started on " + time.ctime())
while(break_count < total_breaks):
browser = subprocess.Popen(['firefox', 'https://www.google.com/'])
sleep(10)
browser.terminate()
break_count = break_count + 1
You need to specify the path to firefox Just like the error shows:
WindowsError: [Error2] The system cannot find the file specified
subprocess.Popen([r'C:\Program Files\Mozilla Firefox\Firefox.exe',
'-new-tab', 'http://www.google.com/'])
Related
I am trying an assignment to open a syslog for a server program (called ticky) that creates logs and errors and then assign the errors to a dictionary and export to a csv file to sort and host to a webpage,
I am unsure of how to access syslog files, as the course only went into sys.argv and I don't know if this can be used or if I need to figure out how to use syslog module. Once the log is opened, the regex will pull the error message and add it to the dictionary, either creating a new entry or adding value to an existing key.
Am I on the right track?
#!/usr/bin/env python3
import re
import sys
errors = {}
# log line format
# Jun 1 11:06:48 ubuntu.local ticky: ERROR: Connection to DB failed (username)
logfile = sys.argv[1]
# NOTE: Check to find correct log file
with open(logfile) as f:
for line in f:
if "ERROR:" not in line:
continue
regex_error = r"ERROR: (\d+) "
"""searches for error messages"""
error = re.search(regex_error, line)
if error is None:
continue
name = error[1]
errors[name] = errors.get(name, 0) + 1
I am trying to test a python code which moves file from source path to target path . The test is done using pytest in Python3 . But I am facing a roadblock here. It is that , I am trying to remove the source and target paths at end of code completion. For this I am using a command like shutil.rmtree(path) or os.rmdir(path) . This is causing me the error - " [WinError 32] The process cannot access the file because it is being used by another process". Please help me on this. Below is the python pytest code :
import pytest
import os
import shutil
import tempfile
from sample_test_module import TestCondition
object_test_condition = TestCondition()
#pytest.mark.parametrize("test_value",['0'])
def test_condition_pass(test_value):
temp_dir = tempfile.mkdtemp()
temp_src_folder = 'ABC_File'
temp_src_dir = os.path.join(temp_dir , temp_src_folder)
temp_file_name = 'Sample_Test.txt'
temp_file_path = os.path.join(temp_src_dir , temp_file_name)
os.chdir(temp_dir)
os.mkdir(temp_src_folder)
try:
with open(temp_file_path , "w") as tmp:
tmp.write("Hello-World\n")
tmp.write("Hi-All\n")
except IOError:
print("Error has occured , please check it.")
org_val = object_test_condition.sample_test(temp_dir)
print("Temp file path is : " + temp_file_path)
print("Temp Dir is : " + temp_dir)
shutil.rmtree(temp_dir)
print("The respective dir path is now removed.)
assert org_val == test_value
Upon execution of the code , the below error is popping up :
[WinError32] The process cannot access the file because it is being used by another process : 'C:\Users\xyz\AppData\Local\Temp\tmptryggg56'
You are getting this error because the directory you are trying to remove is the current directory of the process. If you save the current directory before calling os.chdir (using os.getcwd()), and chdir back to that directory before removing temp_dir, it should work.
Your code isn't correctly indented, so here is my best guess at what it should look like.
import pytest
import os
import shutil
import tempfile
from sample_test_module import TestCondition
object_test_condition = TestCondition()
#pytest.mark.parametrize("test_value",['0'])
def test_condition_pass(test_value):
temp_dir = tempfile.mkdtemp()
temp_src_folder = 'ABC_File'
temp_src_dir = os.path.join(temp_dir , temp_src_folder)
temp_file_name = 'Sample_Test.txt'
temp_file_path = os.path.join(temp_src_dir , temp_file_name)
prev_dir = os.getcwd()
os.chdir(temp_dir)
os.mkdir(temp_src_folder)
try:
with open(temp_file_path , "w") as tmp:
tmp.write("Hello-World\n")
tmp.write("Hi-All\n")
except IOError:
print("Error has occured , please check it.")
org_val = object_test_condition.sample_test(temp_dir)
print("Temp file path is : " + temp_file_path)
print("Temp Dir is : " + temp_dir)
os.chdir(prev_dir)
shutil.rmtree(temp_dir)
print("The respective dir path is now removed.)
assert org_val == test_value
Can you try to close the temp file before removing
temp.close()
I am trying to donwload a huge zip file (~9Go zipped and ~130GO unzipped) from an FTP with python using the ftplib library but unfortunately when using the retrbinary method, it does create the file in my local diretory but it is not writing into the file. After a while the code runs, I get an timeout error. It used to work fine before, but when I tried to go deeper in the use of sockets by using this code it does not work anymore. Indeed, as the files I am trying to download are huge I want to have more control with the connection to prevent timeout error while downloading the files. I am not very familar with sockets so I may have misused it. I have been searching online but did not find any problems like this. (I tried with smaller files too for test but still have the same issues)
Here are the function that I tried but both have problems (method 1 is not writing to file, method 2 donwloads file but I can't unzip it)
import time
import socket
import ftplib
import threading
# To complete
filename = ''
local_folder = ''
ftp_folder = ''
host = ''
user = ''
mp = ''
# timeout error in method 1
def downloadFile_method_1(filename, local_folder, ftp_folder, host, user, mp):
try:
ftp = ftplib.FTP(host, user, mp, timeout=1600)
ftp.set_debuglevel(2)
except ftplib.error_perm as error:
print(error)
with open(local_folder + '/' + filename, "wb") as f:
ftp.retrbinary("RETR" + ftp_folder + '/' + filename, f.write)
# method 2 works to download zip file, but header error when unziping it
def downloadFile_method_2(filename, local_folder, ftp_folder, host, user, mp):
try:
ftp = ftplib.FTP(host, user, mp, timeout=1600)
ftp.set_debuglevel(2)
sock = ftp.transfercmd('RETR ' + ftp_folder + '/' + filename)
except ftplib.error_perm as error:
print(error)
def background():
f = open(local_folder + '/' + filename, 'wb')
while True:
block = sock.recv(1024*1024)
if not block:
break
f.write(block)
sock.close()
t = threading.Thread(target=background)
t.start()
while t.is_alive():
t.join(60)
ftp.voidcmd('NOOP')
def unzip_file(filename, local_folder):
local_filename = local_folder + '/' + filename
with ZipFile(local_filename, 'r') as zipObj:
zipObj.extractall(local_folder)
And the error I get for method 1:
ftplib.error_temp: 421 Timeout - try typing a little faster next time
And the error I get when I try to unzip after using method 2:
zipfile.BadZipFile: Bad magic number for file header
Alos, regarding this code If anyone could explain what this does concerning socketopt too would be helpful:
ftp.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, 75)
ftp.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, 60)
Thanks for your help.
I am creating a tool that gives an overview of hundredths of test results. This tool access a log file, checks for Pass and Fail verdicts. When it is a fail, I need to go back to previous lines of the log to capture the cause of failure.
The linecache.getline works in my workspace (Python Run via eclipse). But after I created a windows installer (.exe file) and installed the application in my computer, the linecache.getline returns nothing. Is there something I need to add into my setup.py file to fix this or is it my code issue?
Tool Code
precon:
from wx.FileDialog, access the log file
self.result_path = dlg.GetPath()
try:
with open(self.result_path, 'r') as file:
self.checkLog(self.result_path, file)
def checkLog(self, path, f):
line_no = 1
index = 0
for line in f:
n = re.search("FAIL", line, re.IGNORECASE) or re.search("PASS", line, re.IGNORECASE)
if n:
currentline = re.sub('\s+', ' ', line.rstrip())
finalresult = currentline
self.list_ctrl.InsertStringItem(index, finaltestname)
self.list_ctrl.SetStringItem(index, 1, finalresult)
if currentline == "FAIL":
fail_line1 = linecache.getline(path, int(line_no - 3)) #Get reason of failure
fail_line2 = linecache.getline(path, int(line_no - 2)) #Get reason of failure
cause = fail_line1.strip() + " " + fail_line2.strip()
self.list_ctrl.SetStringItem(index, 2, cause)
index += 1
line_no += 1
The issue was resolved by doing the get_line function from this link:
Python: linecache not working as expected?
I have made a program that changes the background picture of my desktop every user defined seconds and there is no problems with that part. However I do have a problem with changing the picture of the log in screen I have set up my computer correctly (a windows 7 computer) to change the background picture (including editing the registry to be able to change the picture more then once).
I currently changing my login picture manually by moving the picture to a folder I created C:\windows\system32\oobe\info\backgrounds. I've chosen to make the task automated using python. I will delete the existing image, copy the new image to the folder and then rename the image to backgroundDefault.jpg and repeat every user defined seconds.
To copy, rename, and delete these files using the os module I've tested these steps in my cmd and it works.
Now what seems to be the problem?
Well I'm able to find the folder using os.path.exists however I'm unable to copy, delete or rename anything because the program doesn't have permission.
It is also worth noting that I have already tried to give my user permission to write in the folder and I already tried to give the python programme administrator access not only the python program but Py.exe and th pyw.exe that sit in the wondows folder
Is there a way to give the program permission or is there another way of changing the folder that I need to move the files to? Or even is there a different snipit of script I could use to achieve a login background change?
def path_writer_bg():
folders_path_bg = input("Please type the folders path of the login background here, then press enter"
"\n>")
if os.path.exists(folders_path_bg):
open("your_path_bg.txt", "w").write(folders_path_bg)
read_folder_path_bg = open("your_path_bg.txt", "r").read()
if os.path.exists("task_bg.txt"):
open("task_bg.txt", "w").write("dir " + read_folder_path_bg + " /s /b >listed_bg.txt")
file_read_task_bg = open("task_bg.txt", "r").readline()
else:
open("task_bg.txt", "w").write("dir " + read_folder_path_bg + " /s /b >listed_bg.txt")
file_read_task_bg = open("task_bg.txt", "r").readline()
os.popen(file_read_task_bg)
else:
input("invalid input. press enter to retry \n")
path_writer_bg()
if os.path.exists("your_path_bg.txt"):
read_folder_path_e_bg = open("your_path_bg.txt", "r").read()
open("task_bg.txt", "w").write("dir " + read_folder_path_e_bg + " /s /b >listed_bg.txt")
file_read_task_e_bg = open("task_bg.txt", "r").readline()
os.popen(file_read_task_e_bg)
else:
path_writer_bg()
def everything_bg():
with open("listed_bg.txt") as file_bg:
num_lines_bg = sum(1 for line_bg in open("listed_bg.txt"))
for num_bg, line_bg in enumerate(file_bg, 1):
rand_line_bg = random.randrange(num_lines_bg - 1)
lines_bg = open("listed_bg.txt", "r").readlines()
open('temp_bg.txt', 'w').writelines(lines_bg[rand_line_bg])
wallpaper_bg()
def wallpaper_bg():
path_bg = open("temp_bg.txt", "r").readline()
if os.path.exists("C:\\Windows\\System32\\oobe\\info\\backgrounds\\backgroundDefault.jpg"):
os.popen("del C:\\Windows\\System32\\oobe\\info\\backgrounds\\backgroundDefault.jpg")
else:
pass
if os.popen("copy /y" + path_bg + " C:\\Windows\\System32\\oobe\\info\\backgrounds"):
os.popen("dir C:\\Windows\\System32\\oobe\\info\\backgrounds /s /b >renamer.txt")
else:
pass
if os.path.exists("renamer.txt"):
rename = open("renamer.txt", "r").readline()
else:
pass
os.popen("rename " + rename + "backgroundDefault.jpg")
wallpaper_bg()
exit()
time.sleep(10)
everything()
Maybe it is because that specific file can't be changed with python due to Microsoft not allowing software to change any file in system32.