I am trying to call a python program with subprocess, but I get a permission error. I tried running PyCharm as an admin, but it doesn't help.
My code:
answer = subprocess.check_output("../folder python program %s %s" %(valueA, valueB), encoding = 'utf8')
The error:
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/a/b/b_resolution.py", line 35, in <module>
answer = subprocess.check_output("../folder python program %s %s" %(valueA, valueB), encoding = 'utf8')
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\Lib\subprocess.py", line 376, in check_output
**kwargs).stdout
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\Lib\subprocess.py", line 453, in run
with Popen(*popenargs, **kwargs) as process:
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\Lib\subprocess.py", line 756, in __init__
restore_signals, start_new_session)
File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\Lib\subprocess.py", line 1155, in _execute_child
startupinfo)
PermissionError: [WinError 5] Access Denied
Does someone know how I can fix this permission error?
Although it doesn't answer the original question, this PermissionError also arises if you (accidentally) try to run a directory, instead of a file.
For example, any of these will raise the PermissionError: [WinError 5] Access is denied:
subprocess.check_output('.')
subprocess.run('.')
where '.' represents the path to the current directory, as a minimal example.
On the other hand, if you try to run a non-existent file, you'll get a more useful FileNotFoundError: [WinError 2] The system cannot find the file specified.
Tested with python 3.10.6 on Windows and Ubuntu. On Ubuntu the examples above raise a PermissionError: [Errno 13] Permission denied.
Check the file permissions for your current user.
Right click on the file and in security you can see file permissions for users.
If you haven't permission to read file, Advanced > Select a principal then check this doc.
I fixed the problem by myself the python command comes before the path.
Like this:
answer = subprocess.check_output("python ../folder program %s %s" %(valueA, valueB), encoding = 'utf8')
But I had the problem that it says:
can't find '__main__' module in '../pydig'
Solved that aswell with writing the program name included in the path:
answer = subprocess.check_output("python ../folder/program %s %s" %(valueA, valueB), encoding = 'utf8')
close file explorer...
dumb but if you have the folder open in the explorer and you're trying to do anything to the folders/files you'll get this error
Don't run in Visual Studio 🤣. It happened to me just now.
Related
As part of larger code, I am trying to make a function that calls to a latexmk compiler using subprocess, but I consistently get FileNotFoundError: [Errno 2] No such file or directory: 'latexmk': 'latexmk'
However, If I write the command directly in the terminal, everything works: latexmk --pdf test.tex
In case it is important, I am on MacOS Mojave 10.14.6, running python 3.6 spyder through anaconda
I have checked the following links:
https://askubuntu.com/questions/801493/python-subprocess-call-not-working-as-expected
OSError: [Errno 2] No such file or directory while using python subprocess in Django
Running Bash commands in Python
If anything there solves the problem, I missed it.
To make everyone's life easier, here's a link to a .tex file [you can use your own]:
https://drive.google.com/open?id=1DoJnvg2BmbRCzmRmqFYRVybyTQUtyS-h
Afer putting type latexmk to terminal it outputs:
latexmk is hashed (/Library/TeX/texbin/latexmk)
Here is the minimal reproducible example (you do need latexmk on your computer though):
import os, subprocess
def pdf(file_path):
cur_dir = os.getcwd()
dest_dir = os.path.dirname(file_path)
basename = os.path.basename(file_path)
os.chdir(dest_dir)
main_arg = [basename]
command = ["latexmk", "--pdf"] + main_arg
try:
output = subprocess.check_output(command)
except subprocess.CalledProcessError as e:
print(e.output.decode())
raise
os.chdir(cur_dir)
pdf("path to your .tex file")
I have a feeling that I am grossly misunderstanding the way subprocess works. Any ideas?
Update: In case neccessary, the full traceback:
Traceback (most recent call last):
File "<ipython-input-90-341a2810ccbf>", line 1, in <module>
pdf('/Users/sergejczan/Desktop/untitled folder/test.tex')
File "/Users/sergejczan/Desktop/Lab/subprocess error reproduction.py", line 23, in pdf
output = subprocess.check_output(command)
File "/anaconda3/lib/python3.6/subprocess.py", line 336, in check_output
**kwargs).stdout
File "/anaconda3/lib/python3.6/subprocess.py", line 403, in run
with Popen(*popenargs, **kwargs) as process:
File "/anaconda3/lib/python3.6/subprocess.py", line 709, in __init__
restore_signals, start_new_session)
File "/anaconda3/lib/python3.6/subprocess.py", line 1344, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
FileNotFoundError: [Errno 2] No such file or directory: 'latexmk': 'latexmk'
New Update
Changing the output = subprocess.check_output(command) line with the hardcoded envirnoment that I got from echo $PATH worked wonderfully.
output = subprocess.check_output(command,env = {'PATH': '/anaconda3/bin:/Users/sergejczan/anaconda3/bin:/Users/sergejczan/Desktop/Lab/anaconda2/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/TeX/texbin'})
Would you think that there is a way to make the code find the PATH automatically?
I've been trying to get the output of the following command 'manage-bde -status' which works fine on my windows cmd commande prompt, but by using a python program.The same command doesn't work on python subprocess, so I had to launch the manage-bde.exe file.
So my code looks like this now :
import os, platform, subprocess
################This part is only helpful for resolving 32 bit/64 bits issues##########
system_root = os.environ.get('SystemRoot', 'C:\\Windows');
if (platform.architecture()[0] == '32bit' and platform.machine() == 'AMD64'):
system32='Sysnative'
else:
system32='System32'
manage_bde = os.path.join(system_root, system32, 'manage-bde.exe')
print(manage_bde)
#######################################################################################
stdout=subprocess.check_output(['start',manage_bde,'-status'])
print('Output:'+stdout)
I'm launching it from cmd commande line, with Python 3.7.0. The problem is that I get the following output :
C:\WINDOWS\Sysnative\manage-bde.exe (this is from my print(manage_bde))
Traceback (most recent call last):
File "testCLI.py", line 13, in <module>
stdout=subprocess.check_output(['start',manage_bde,'-status'])
File "d:\Profiles\user\AppData\Local\Programs\Python\Python3\lib\subprocess.py", line 376, in check_output
**kwargs).stdout
File "d:\Profiles\user\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 453, in run
with Popen(*popenargs, **kwargs) as process:
File "d:\Profiles\user\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 756, in __init__
restore_signals, start_new_session)
File "d:\Profiles\user\AppData\Local\Programs\Python\Python37-32\lib\subprocess.py", line 1155, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] Specified file was not found
I launch it from the D: Drive. Does anyone know what I missed ?
You probably need to run the script with administrator privileges.
If the file exists in the filesystem and you get FileNotFoundError: [WinError 2], you can test whether the the script has enough permissions to see the file with:
os.stat(manage_bde)
Yes I have enough permissions to see the file : the os.stat(manage_bde) is working.
I have changed my parameters like eryksun proposed :
stdout = subprocess.getoutput([manage_bde, '-status'])
Now I can launch the program (but only with a shell with administrator rights) and get the output, thank you !
I'm trying to use a piece of software called "bundler_sfm" which is executed using a python script.
The software I'm trying to use is available here, the script is in the utils directory if you want to have a look.
When trying to run it I get the following python error:
File "/usr/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 679, in __init__
errread, errwrite)
File "/usr/lib/python2.7/subprocess.py", line 1249, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
The code that leads to this error is as follows:
# Extract SIFT data
if verbose:
with open(pgm_filename, 'rb') as fp_in:
with open(key_filename, 'wb') as fp_out:
subprocess.call(BIN_SIFT, stdin=fp_in, stdout=fp_out)
I've looked at various other answers with similar errors but am still at a loss on how to fix this problem.
I'm trying to run this in the terminal on elementary OS.
Any assistance would be greatly appreciated.
Already worked it out in the comments, but just for an answer:
Worked out the location where the utility thinks the sift binary is located by printing out BIN_SIFT before calling subprocess.call() method.
Realized this path was incorrect
As a hackish work-around, hard code the correct path to line 55 of bundler.py as a string inside of a list:
BIN_SIFT = ["/real/path/to/sift"]
I have a problem with running files through python.
This is my code :
def report1(self):
str="/Users/Apple/Desktop/Report1.exe"
subprocess.call(str)
This is the error i am getting :
File "./DBMS.py", line 427, in <module>
Main().run();
File "./DBMS.py", line 415, in run
self.report1()
File "./DBMS.py", line 383, in report1
subprocess.call(str)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 524, in call
return Popen(*popenargs, **kwargs).wait()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 711, in __init__
errread, errwrite)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1308, in _execute_child
raise child_exception
OSError: [Errno 13] Permission denied
PS: i tried changing permission rights on folders and i tried using subprocress.Popen .
i also tried adding shell=True. i don't understand why its still not working .
any help is really appreciated.
have to submit in 24 hours :(
For all its merits, subprocess doesn't make it abundantly clear when an error has occurred while trying to execute a command.
If the deepest frame in your traceback (the one right before the actual exception) is raise child_exception from subprocess.py, that means there was some issue inclusively between the fork(2) and exec*(2) calls -- in other words, that an error occurred while trying to run the command you requested.
The actual exception you pasted was OSError: [Errno 13] Permission denied. An errno of 13 corresponds to EACCES:
>>> import errno; print errno.errorcode[13]
EACCES
If you've never used fork(2) or exec(2) things will be pretty inscrutable, because subprocess has dropped the real traceback. However, I can tell you that this OSError almost certainly came from the exec* call. It turns out execve raises this under the following conditions:
[EACCES] Search permission is denied for a component of the
path prefix.
[EACCES] The new process file is not an ordinary file.
[EACCES] The new process file mode denies execute permission.
[EACCES] The new process file is on a filesystem mounted with
execution disabled (MNT_NOEXEC in <sys/mount.h>).
(Courtesy of Apple)
If I had to guess, you encountered this this exception because the command you're trying to run isn't marked executable (with something like chmod u+x).
Now, it's unlikely that your .exe file will run on your Mac after solving this, but at least it'll be a different error!
Try running your program as sudo:
sudo python mycode.py
I have a simple python script that works fine on Linux, I moved it to a Windows machine and when I attempt to run it, I get the following exception message:
Traceback (most recent call last):
File "C:\path\to\my\script.py", line 57, in <module>
retcode = subprocess.call(command)
File "C:\Python27\lib\subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
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 5] Access is denied
Here is the snippet of code that throws the exception:
print 'command is:',command
retcode = subprocess.call(command)
The console out put is as follows:
command is: ['c:\python27', 'C:\path\to\script.py', '--mode=2', '--check-temp=false', '--all-seasons=true', '--added=1', '--max-temp=2000', '--source=2', '--loc=XYZ']
Unhandled exception while debugging...
Anyone knows how to fix this?
I am running python v2.7.3 on Windows XP Professional
According to the documentation, the first item in the argument sequence (in this case, the first element of command) is interpreted as the program to execute.
Looking at the first element of command, it would appear that you're trying to execute a directory. Windows (somewhat non-intuitively) returns an access denied error whenever you try to read from a directory as if it were a file, and the same thing happens if you try to execute one.
Instead of c:\python27 you probably want c:\python27\bin\python.exe or something similar. At any rate, you need to be pointing at the executable, not at the directory. I'm not sure why this works for you on Linux.
Your program doesn't have access to the file... check permissions on the file you're trying to access, then go from there... (ie, either elevate the Python interpreter's permissions, or reduce access required to said resource) - either way - tread carefully.