I am stuck with my script at a point. The script is this
import subprocess
import os
def Windows():
SW_MINIMIZE = 6
info = subprocess.STARTUPINFO()
info.dwFlags = subprocess.STARTF_USESHOWWINDOW
info.wShowWindow = SW_MINIMIZE
print(os.path.isdir("C:\Program Files (x86)"))
while True:
try:
subprocess.Popen(r'C:\Program Files (x86)\Mozilla Firefox\firefox.exe', startupinfo=info)
except WindowsError:
subprocess.Popen(r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe', startupinfo=info)
else:
try:
subprocess.Popen(r'C:\Program Files\Mozilla Firefox\firefox.exe', startupinfo=info)
except WindowsError:
subprocess.Popen(r'C:\Program Files\Google\Chrome\Application\chrome.exe', startupinfo=info)
What I want to do is check if the computer is 64 bit or 32 bit (as I want to open the browser without a window using subprocess.) to locate the browsers chrome or firefox, depending on which one the user has ( I am assuming that they have either one of them). Since the path for chrome and firefox varies in 64 vs 32 bit computers (Program Files and Program Files (x84)), I came up with this script which detects if x86 folder exists or not. If it does, it continues on the folder for searching for the browsers. However, if it doesn't, it assumes it is 32-bit and searches for Program Files folder and in that folder it searches for the browsers.
However, when I run the script I get this error
Traceback (most recent call last):
File "C:\Users\Charchit\Desktop\via.py", line 29, in <module>
Windows()
File "C:\Users\Charchit\Desktop\via.py", line 13, in Windows
subprocess.Popen(r'C:\Program Files (x86)\Google\Chrome\Application\chrome.exe', startupinfo=info)
File "C:\Python27\lib\subprocess.py", line 710, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 958, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
However, in my script it should not even go to while True Section because I have a 32 bit system and x86 folder doesn't exist!
You're not actually checking if os.path.isdir("C:\Program Files (x86)"). You're just printing it.
Instead of
print(os.path.isdir("C:\Program Files (x86)"))
while True:
You need to do
if os.path.isdir(r"C:\Program Files (x86)"):
Side note:
Both chrome and firefox traditionally place themselves on the path, so there's a good chance you can just do subprocess.Popen('firefox.exe') / subprocess.Popen('chrome.exe').
for creating the path use the built-ins python functions that won't mess up the path
if os.path.exists(os.path.join('C:', os.path.sep(), 'Program Files')):
# do your stuff
Related
Firstly, I'd just like to say my level of python programming is absolute beginner so please be patient!
I've installed Python 3.7.4, along with some packages such as numpy, xlwings and (most importantly) selenium.
I've downloaded the this onto my 64-bit windows 10 laptop and followed the advice of the Python forum to address issues particular to Windows but still, when I try to run a slightly modified version of this example code which basically opens a browser (the sample opens firefox, I'm using Chrome - they both have this same issue!), navigates to facebook and logs-in.
My code is:
from selenium import webdriver
import time
username = 'fb_email#email.com'
password = 'fb_password'
url = 'https://www.facebook.com/'
driver = webdriver.Chrome(executable_path=r"C:\\Python37\\Lib\\site-packages\\selenium\\webdriver\\chrome\\webdriver.py")
driver.get(url)
driver.find_element_by_id('email').send_keys(username)
driver.find_element_by_id('pass').send_keys(password)
time.sleep(2)
driver.find_element_by_id('loginbutton').click()
When I run this code I'm getting the following error message:
Traceback (most recent call last):
File
"C:/Python37/Codes/Test.py", line 9, in
driver = webdriver.Chrome(r"C:\Python37\Lib\site-packages\selenium\webdriver\chrome\webdriver.py")
File
"C:\Python37\lib\site-packages\selenium\webdriver\chrome\webdriver.py",
line 73, in init
self.service.start() File "C:\Python37\lib\site-packages\selenium\webdriver\common\service.py",
line 76, in start
stdin=PIPE) File "C:\Python37\lib\subprocess.py", line 775, in init
restore_signals, start_new_session) File "C:\Python37\lib\subprocess.py", line 1178, in _execute_child
startupinfo) OSError: [WinError 193] %1 is not a valid Win32 application
You'll notice one other change I've made from the original code is I've include the full file path (explicitly referencing Webdrive.py file) to deal with the "permissions" error.
Basically, I just want to get to the stage I can run this code and I can do I know I can run selenium on python in principal and deal with the nested looping within the python code at a later date so any help/suggestions would be greatly appreciated.
Root Cause:
You are not providing the correct path to the executable_path in line # 9. executable_path should point to the chromedriver.exe path not the p.py path.
How to fix:
Update the line#9 with the correct path to the chromedriver.exe.
# make sure you add `.exe` file name too at the end like `chromedriver.exe`.
driver = webdriver.Chrome(executable_path=r"pathToChromedriver")
I'm trying to download some files at regular intervals, remove the old ones and replace them with new files. First time it runs well, but the second time it throws an error.
def check_update():
print ('looking for update')
shutil.rmtree(config.destination)
shutil.os.mkdir(config.destination)
threading.Timer(60.0,check_update).start()
def get_videos():
response = requests.get(config.api)
data = response.json()
files = list()
l = len(data)
for i in range(l):
files.append(data[i]['filename'])
return files
def get_newfiles(myfiles):
for i in range(len(myfiles)):
url = config.videos+myfiles[i]
filename = wget.download(url)
def move_files(myfiles):
for i in range(len(myfiles)):
file = myfiles[i]
shutil.move(config.source_files+file,config.destination)
def videos():
files = set(get_videos())
myfiles = list(files)
get_newfiles(myfiles)
move_files(myfiles)
videos()
print ("files are updated")
res = requests.get(config.api)
data = res.json()
return data
data = check_update()
Here is the error.
File "C:\Program Files (x86)\Python36-32\lib\threading.py", line 916, in _bootstrap_inner
self.run()
File "C:\Program Files (x86)\Python36-32\lib\threading.py", line 1182, in run
self.function(*self.args, **self.kwargs)
File "tornado.py", line 8, in check_update
shutil.rmtree(config.destination)
File "C:\Program Files (x86)\Python36-32\lib\shutil.py", line 494, in rmtree
return _rmtree_unsafe(path, onerror)
File "C:\Program Files (x86)\Python36-32\lib\shutil.py", line 389, in _rmtree_unsafe
onerror(os.unlink, fullname, sys.exc_info())
File "C:\Program Files (x86)\Python36-32\lib\shutil.py", line 387, in _rmtree_unsafe
os.unlink(fullname)
permissionError: [WinError 32] The process cannot access the file because it is being used by another process:
How can I overcome this?
The error occurs when attempting to delete config.destination dir. That happens because either the dir itself or one (or more) of its children (may be a dir or a file) is opened in another process (could also be the current one).Typical usecases that frequently lead to this situation:
A cmd console is open in that dir. Just cd outside the dir and try removing it again
A running program has a file opened
As an example could be a Notepad (or an IDE) that has opened a source file located in that dir.
But since it looks like you work with videos, maybe You wanted to check whether a downloaded file works and opened it in a video player.
No matter what the case, closing that program would fix the issue
This is specific to you: I don't know how wget.download works, but if it's not blocking (although according to the code it doesn't seem to be the case) maybe one video from your previous run is still downloading, hence it's open. Closing that python process would do (whether waiting til it finishes or killing it from Task Manager)
Note: When searching for the cause, you should try removing the dir from a file manager (e.g. Windows Explorer) to avoid the overhead introduced by the script.
Question: How can I change file permissions on a Windows 10 PC with a Python script?
I have written a Python script that takes folders, which are created by proprietary software, and moves them to a network drive with shutil.move().
It seems that the proprietary software creates folders that are read-only by default. I need to change the file permissions for these folders in order for shutil.move() to delete the folders after they are copied to the network drive.
I have searched on SO to discover that os.chmod(path, 0o777) only works to grant access on Unix systems. On Windows, it modifies the read-only attribute of a file or folder. This question seems to yield a solution, which I tried as follows:
import win32security
import ntsecuritycon as con
account = r"admin"
userx, domain, type = win32security.LookupAccountName ("", account)
sd = win32security.GetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION)
dacl = sd.GetSecurityDescriptorDacl() # instead of dacl = win32security.ACL()
dacl.AddAccessAllowedAce(win32security.ACL_REVISION, con.FILE_GENERIC_READ | con.FILE_GENERIC_WRITE, userx)
sd.SetSecurityDescriptorDacl(1, dacl, 0) # may not be necessary
win32security.SetFileSecurity(path, win32security.DACL_SECURITY_INFORMATION, sd)
But it does not seem to work. Also, I don't understand what I am doing with the modules win32security and ntsecuritycon. Maybe someone can give an easy explanation.
edit: ok so i looked at stuff. This is the exception that gets raised:
Traceback (most recent call last):
File "copyscript.py", line 108, in <module>
copyscript()# the loop needs to be called as a function to delete all assigned variables after each loop
File "copyscript.py", line 93, in copyscript
shutil.move(run, str(target_dir2))#move files renamed to user folder
File "C:\Users\admin\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 550, in move
rmtree(src)
File "C:\Users\admin\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 488, in rmtree
return _rmtree_unsafe(path, onerror)
File "C:\Users\admin\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 378, in _rmtree_unsafe
_rmtree_unsafe(fullname, onerror)
File "C:\Users\admin\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 383, in _rmtree_unsafe
onerror(os.unlink, fullname, sys.exc_info())
File "C:\Users\admin\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 381, in _rmtree_unsafe
os.unlink(fullname)
PermissionError: [WinError 5] Access is denied: 'THG126.D\\AcqData\\sample_info.xml'
the full path of this file is D:\MSD_Data\THG126.D\AcqData\sample_info.xml.
the user account is named "admin" and it belongs to the "Administrators" group.
"admin" is the owner and has "full control" according to the "advanced security settings" for MSD_Data, THG126.D, sample_info.xml and the python script.
i have also tried running the script via CLI using "run as administrator". The same error occurs.
i looked at all files in the folders and found that only sample_info.xml has RA attributes, whereas all other have only A, so i added
path2 = r"D:\\MSD_data\\"+run+r"\\AcqData\\sample_info.xml"
subprocess.check_call(["attrib", "-r", path2, "/S", "/D"])
to the script and it seems to work now. I need to wait a little for new folders to be generated by the other software to see if the script is working correctly now.
The problem seems to have been that a file had the attribute "RA", which means "read-only" and "archived". Even though the used user account wqas the owner of all files and folders, shutil.move() fails when it tries to delete the file after copying to the target location.
A workaround to this problem is to use
subprocess.check_call(["attrib", "-r", path])
to remove the read-only file attribute. This resolved my issue. If you still have trouble with shutil.move() you could also try this solution.
I'm writing a simple fuzzer for use on Windows applications based on the Charlie Miller code from the babysitting an army of monkeys talk. However I keep receiving the error
Traceback (most recent call last):
File "D:/Python27/fuzzer.py", line 29, in <module>
process=subprocess.Popen([app_choice,fuzz_output])
File "D:\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "D:\Python27\lib\subprocess.py", line 896, in _execute_child
startupinfo)
WindowsError: [Error 5] Access is denied
Does anyone know how to bypass this? I'm really stumped because I'm not all too familiar with Windows 7 permissions or Python 2.7 to be honest. Full code below
#List of file names (all located in the python folder)
fuzz_files=[ "slides_algo-guiding.pdf", "slides_algo-intro-annotated- final.pdf","slides_algo-merge1.pdf"]
apps=["C:\Program Files (x86)\Adobe\Reader 9.0\Reader"
]
#Creates an output file in the Python folder
fuzz_output="fuzz.pdf"
FuzzFactor=50
num_tests=1000
import math
import string
import random
import subprocess
import time
for i in range(num_tests):
file_choice=random.choice(fuzz_files)
app_choice=random.choice(apps)
buf=bytearray(open(file_choice,'rb').read())
#Charlie Miller code
numwrites=random.randrange(math.ceil((float(len(buf))/FuzzFactor)))+1
for j in range(numwrites):
rbyte=random.randrange(256)
rn=random.randrange(len(buf))
buf[rn]="%c"%(rbyte)
#End Charlie miller code
#Write code
open(fuzz_output,'wb').write(buf)
process=subprocess.Popen([app_choice,fuzz_output])
time.sleep(1)
crashed=process.poll()
if not crashed:
process.terminate()
I believe that C:\Program Files (x86)\Adobe\Reader 9.0\Reader is the path of a folder, not an executable. Therefore trying to run it with Popen makes no sense.
Also, you should be using raw strings when writing Windows paths r"C:\Program Files (x86)\Adobe\Reader 9.0\Reader\AcroRd32.exe" or using slashes instead "C:/Program Files (x86)/Adobe/Reader 9.0/Reader/AcroRd32.exe". You were just lucky that there weren't any valid escape sequences in the paths.
I have encountered an error which I am not able to resolve.
I am trying to perform the easiest set of commands that will perform a tBLASTn algorithm,
looking for a sequence (sequence specified as a "pytanie.fasta" file) in a database (also specified as file -> cucumber.fasta). The result will be saved in the "wynik.txt" file.
The code looks as following:
from Bio.Blast. Applications import NcbitblastnCommandline
database = r"\Biopython\cucumber.fasta"
qr = r"\Biopython\pytanie.fasta"
output = r"\Biopython\wynik.txt"
e = raw_input("Enter e-value: ")
tblastn_cline = NcbitblastnCommandline(cmd='blastn', db=database, query=qr, out=output, evalue=e, outfmt=7)
print tblastn_cline
stdout, stderr = tblastn_cline()
And the error I get:
File "C:\Users\IBM_ADMIN\Desktop\PYTHON\Workspace\Biopython\blast.py", line 20, in <module>
stdout, stderr = tblastn_cline()
File "C:\Python27\lib\site-packages\Bio\Application\__init__.py", line 435, in __call__
shell=(sys.platform!="win32"))
File "C:\Python27\lib\subprocess.py", line 679, in __init__
errread, errwrite)
File "C:\Python27\lib\subprocess.py", line 893, in _execute_child
startupinfo)
WindowsError: [Error 2] The system cannot find the file specified
I am using:
Eclipse SDK Version: 3.7.1
Python version 2.7
OS: 64 bit Windows 7
I have tried this also on 32-bit Windows XP and it produces the same error.
Biopython package should work fine since it went through the tests suggested by biopython website. I have also tried other formats of the path where the files are located, but it did not work. My friend uses the same code on Ubuntu and it works fine.
Does anybody know how to fix this error?
What are the paths of the files?
The path r"\Biopython\cucumber.fasta", for example, is an absolute path on the current drive (because it starts with a backslash and no drive letter), which I think in your case is r"C:\Biopython\cucumber.fasta". Is that correct?