sorry if it's stupid, not clear or not even the good place to ask...
in order to get sys.argv from a file (drag and dropping it), i've made an automator app .
here is the code fromthe script.py :
#!/usr/bin/env python3
import sys
import os
file=sys.argv[1:][0]
print(file)
try:
os.makedirs(('/'.join(file.split('/')[:-1]))+"/new")
except:
OSError
pass
so basicaly i drag and drop a file on my"app" ,in the file directory,the scripts makes a new folder.
but i can't see myprintoutput anywhere
How could I have a console showing me what happens ( in windows, i use a DAT file that runs the script, but everything is traced in the CMD )
thanks a lot
guillaume
Hum I am not sure I understand the question ....
so I might not bring the right answer.
1) run your code from the Powershell ( make sure your python is properly link...)
2) add under "os.makedirs...." (for python 3) :
print ( '/'.join(file.split('/')[:-1]))+"/new" )
3) save and run
if it solves the your problem , consider it as answer, I need points ..... :)
I'm writing a program that I would like to make a stand alone for my company. It works perfectly when I run it from the sublime text shell and I have everything set up to go except one issue that I can't seem to solve; file paths that involve usernames. Does anyone have any suggestion on how to handle this?
An example is
wb.save(r'C:\Users******\Desktop\Excel.xlsx')
I want to make the ****** part either be automatic or an input box.
Use os.path.expanduser() with '~' where you want the home directory:
import os
print(os.path.expanduser('~/Desktop/Excel.xlsx'))
Alternatively use pathlib.Path:
from pathlib import Path
print(Path.home() / 'Desktop' / 'Excel.xlsx')
os.getlogin() will do
import os
path = os.path.join(r'C:\Users',os.getlogin(),'Desktop','Excel.xlsx')
print(path)
Awesome! Looks like that worked but it presented another error now when I create it as a stand alone.
Wait originally works when I run it from the shell using this code, where EC is expected conditions:
wait.until(EC.frame_to_be_available_and_switch_to_it(driver.find_element_by_name('AppBody')))
Whenever I run it as a stand alone though I get the following error:
Traceback (most recent call last):
File "Stand_Alone_CAS_Automation", line 57, in <module>
NameError: name 'wait' is not defined
[17344] Failed to execute script Stand_Alone_CAS_Automation
I'm trying to run an R Script through Python using subprocess but unfortunately, I'm continually getting the following error:
WindowsError: [Error 2] The system cannot find the file specified
This is extremely frustrating as I've checked the path over everything multiple times (done it without C:/, moved to different directories, changed the R script I'm trying to run, etc). I've also checked the CompSec Environment Variable, and it is also correct (through Windows Systems, although I never checked it directly in my IDE, Spyder). I've tried doing it in Python 2.7 and Python 3.5, and neither version works.
The code goes as follows:
import subprocess
def sort_ByInputColumn(inputPath, inputFileTermination, sortColumn, outputPath, outputFileTermination):
scriptPath = "C:/Users/Kyle/Documents/Rscript_SortByInputColumn.R"
subprocess.call(["Rscript", scriptPath, inputPath, inputFileTermination, sortColumn, outputPath, outputFileTermination])
fileName = 'Alabama'
outputPath = "C:/Users/Kyle/Documents/HillData/Data/Output/Module2/"
sortColumn = str(16)
inputTermination = fileName + 'Module2NN_WorkCounty_Work.csv'
outputFileTermination = fileName + 'Module2NN_SortedWorkCounty.csv'
sort_ByInputColumn(outputPath, inputTermination, sortColumn, outputPath, outputFileTermination)
The fact that I get this error no matter what code I try to run (even blatantly copy-pasting this tutorial to try and make it work) makes me feel like something deeper (or something extremely obvious) is going on that I'm not seeing.
Would appreciate any feedback on the matter.
To solve this most annoying and horrendous problem, I reinstalled R into a directory with no spaces and called Rscript with its full pathing (that is "C:/R/R-3.3.1/bin/Rscript.exe" from C:/Program Files/R/R-3.3.1/bin/Rscript.exe" because Program Files has a space and this kills subprocess because it's command line based, I guess). This time, it worked.
See this similar question for a hint as to where I got the inspiration for this.
I'm getting this error :
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python34\lib\tkinter\__init__.py", line 1538, in __call__
return self.func(*args)
File "C:/Users/Marc/Documents/Programmation/Python/Llamachat/Llamachat/Llamachat.py", line 32, in download
with open(place_to_save, 'wb') as file:
PermissionError: [Errno 13] Permission denied: '/goodbye.txt'
When running this :
def download():
# get selected line index
index = films_list.curselection()[0]
# get the line's text
selected_text = films_list.get(index)
directory = filedialog.askdirectory(parent=root,
title="Choose where to save your movie")
place_to_save = directory + '/' + selected_text
print(directory, selected_text, place_to_save)
with open(place_to_save, 'wb') as file:
connect.retrbinary('RETR ' + selected_text, file.write)
tk.messagebox.showwarning('File downloaded',
'Your movie has been successfully downloaded!'
'\nAnd saved where you asked us to save it!!')
Can someone tell me what I am doing wrong?
Specs :
Python 3.4.4 x86
Windows 10 x64
This happens if you are trying to open a file, but your path is a folder.
This can happen easily by mistake.
To defend against that, use:
import os
path = r"my/path/to/file.txt"
assert os.path.isfile(path)
with open(path, "r") as f:
pass
The assertion will fail if the path is actually of a folder.
There are basically three main methods of achieving administrator execution privileges on Windows.
Running as admin from cmd.exe
Creating a shortcut to execute the file with elevated privileges
Changing the permissions on the python executable (Not recommended)
A) Running cmd.exe as and admin
Since in Windows there is no sudo command you have to run the terminal (cmd.exe) as an administrator to achieve to level of permissions equivalent to sudo. You can do this two ways:
Manually
Find cmd.exe in C:\Windows\system32
Right-click on it
Select Run as Administrator
It will then open the command prompt in the directory C:\Windows\system32
Travel to your project directory
Run your program
Via key shortcuts
Press the windows key (between alt and ctrl usually) + X.
A small pop-up list containing various administrator tasks will appear.
Select Command Prompt (Admin)
Travel to your project directory
Run your program
By doing that you are running as Admin so this problem should not persist
B) Creating shortcut with elevated privileges
Create a shortcut for python.exe
Righ-click the shortcut and select Properties
Change the shortcut target into something like "C:\path_to\python.exe" C:\path_to\your_script.py"
Click "advanced" in the property panel of the shortcut, and click the option "run as administrator"
Answer contributed by delphifirst in this question
C) Changing the permissions on the python executable (Not recommended)
This is a possibility but I highly discourage you from doing so.
It just involves finding the python executable and setting it to run as administrator every time. Can and probably will cause problems with things like file creation (they will be admin only) or possibly modules that require NOT being an admin to run.
Make sure the file you are trying to write is closed first.
Change the permissions of the directory you want to save to so that all users have read and write permissions.
You can run CMD as Administrator and change the permission of the directory using cacls.exe. For example:
cacls.exe c: /t /e /g everyone:F # means everyone can totally control the C: disc
In my case the problem was that I hid the file (The file had hidden atribute): How to deal with the problem in python:
Edit: highlight the unsafe methods, thank you d33tah
# Use the method nr 1, nr 2 is vulnerable
# 1
# and just to let you know there is also this way
# so you don't need to import os
import subprocess
subprocess.check_call(["attrib", "-H", _path])
# Below one is unsafe meaning that if you don't control the filePath variable
# there is a possibility to make it so that a malicious code would be executed
import os
# This is how to hide the file
os.system(f"attrib +h {filePath}")
file_ = open(filePath, "wb")
>>> PermissionError <<<
# and this is how to show it again making the file writable again:
os.system(f"attrib -h {filePath}")
file_ = open(filePath, "wb")
# This works
I had a similar problem. I thought it might be with the system. But, using shutil.copytree() from the shutil module solved the problem for me!
The problem could be in the path of the file you want to open. Try and print the path and see if it is fine
I had a similar problem
def scrap(soup,filenm):
htm=(soup.prettify().replace("https://","")).replace("http://","")
if ".php" in filenm or ".aspx" in filenm or ".jsp" in filenm:
filenm=filenm.split("?")[0]
filenm=("{}.html").format(filenm)
print("Converted a file into html that was not compatible")
if ".aspx" in htm:
htm=htm.replace(".aspx",".aspx.html")
print("[process]...conversion fron aspx")
if ".jsp" in htm:
htm=htm.replace(".jsp",".jsp.html")
print("[process]..conversion from jsp")
if ".php" in htm:
htm=htm.replace(".php",".php.html")
print("[process]..conversion from php")
output=open("data/"+filenm,"w",encoding="utf-8")
output.write(htm)
output.close()
print("{} bits of data written".format(len(htm)))
but after adding this code:
nofilenametxt=filenm.split('/')
nofilenametxt=nofilenametxt[len(nofilenametxt)-1]
if (len(nofilenametxt)==0):
filenm=("{}index.html").format(filenm)
It Worked perfectly
in my case. i just make the .idlerc directory hidden.
so, all i had do is to that directory and make recent-files.lst unhidden after that, the problem was solved
I got this error as I was running a program to write to a file I had opened. After I closed the file and reran the program, the program ran without errors and worked as expected.
I faced a similar problem. I am using Anaconda on windows and I resolved it as follows:
1) search for "Anaconda prompt" from the start menu
2) Right click and select "Run as administrator"
3) The follow the installation steps...
This takes care of the permission issues
Here is how I encountered the error:
import os
path = input("Input file path: ")
name, ext = os.path.basename(path).rsplit('.', 1)
dire = os.path.dirname(path)
with open(f"{dire}\\{name} temp.{ext}", 'wb') as file:
pass
It works great if the user inputs a file path with more than one element, like
C:\\Users\\Name\\Desktop\\Folder
But I thought that it would work with an input like
file.txt
as long as file.txt is in the same directory of the python file. But nope, it gave me that error, and I realized that the correct input should've been
.\\file.txt
As #gulzar said, I had the problem to write a file 'abc.txt' in my python script which was located in Z:\project\test.py:
with open('abc.txt', 'w') as file:
file.write("TEST123")
Every time I ran a script in fact it wanted to create a file in my C drive instead Z!
So I only specified full path with filename in:
with open('Z:\\project\\abc.txt', 'w') as file: ...
and it worked fine. I didn't have to add any permission nor change anything in windows.
That's a tricky one, because the error message lures you away from where the problem is.
When you see "__init__.py" of an imported module at the root of an permission error, you have a naming conflict. I bed a bottle of Rum, that there is "from tkinter import *" at the top of the file. Inside of TKinter, there is the name of a variable, a class or a function which is already in use anywhere else in the script.
Other symptoms would be:
The error is prompted immediately after the script is run.
The script might have worked well in previous Python versions.
User Mixon's long epos about administrator execution privileges has no impact at all. There would be no access errors to the files mentioned in the code from the console or other pieces of software.
Solution:
Change the import line to "import tkinter" and add the namespace to tkinter methods in the code.
Two easy steps to follow:
Close the document which is used in your script if it's open in your PC
Run Spyder from the Windows menu as "Run as administrator"
Error resolved.
This error actually also comes when using keras.preprocessing.image so for example:
img = keras.preprocessing.image.load_img(folder_path, target_size=image_size)
will throw the permission error. Strangely enough though, the problem is solved if you first import the library: from keras.preprocessing import image and only then use it. Like so:
img = image.load_img(img_path, target_size=(180,180))
If the title isn't clear enough the directory has Developer/Pythonfiles/Pong has Pong.py and hit.wav in it.
When i run ~ $python Developer/Pythonfiles/Pong/Pong.py
The sound hit.wav won't play, A weird popping noise plays instead.
But when I run ~/Developer/Pythonfiles/Pong $python Pong.py the sound from hit.wav plays as expected.
Why doesn't the program Pong.py search the directory its in rather than my working directory for Hit.wav? I try to access hit.wav with hit = pygame.mixer.Sound("hit.wav") and play it with hit.play()
Because it has no way of automagically knowing that's what you wanted. So specify the desired behaviour yourself:
import os
hit = pygame.mixer.Sound(os.path.join(os.path.dirname(__file__), "hit.wav"))