So my issue is that I have an AWS EC2 instance running Ubuntu server 18.04 and Apache2, when a button is pressed it posts some variables which are passed to a function which then uses shell_exec() to execute a Python script. The Python script then takes these variables (direction and angle) as command line arguments, it will then attempt to write then to a file called cmds.txt. When doing this however I get this error reported back to me:
Traceback (most recent call last):
File "/home/server/cmdWriter.py", line 45, in
main()
File "/home/server/cmdWriter.py", line 41, in main
servoCmds(direction, angle)
File "/home/server/cmdWriter.py", line 28, in servoCmds
cmdFile = open("cmds.txt", "a")
PermissionError: [Errno 13] Permission denied: 'cmds.txt'
After some looking I think this is because PHP executes as user "www-data" which doesn't have write privileges, so after looking at other questions I tried settung up permissions so that www-data has read and write privilages to the folder and the python file. For whatever reason this does not work! I've been pulling my hair out trying to get this to work, trying suggestions from several other questions, can anyone help me here?
You are getting the error with respect to 'opening' the file. You have to make sure that the permissions on the .txt file are at 755 or higher. If the server you are using is Linux, then you have two alternatives to modify the permissions:
If you have cPanel, you can use the cPanel interface and just change permissions by going to the file, click on Change Permissions and then set the permissions to 777.
or
From the linux command line, use chmod command - like this:
chmod 777 cmds.txt
I can't speak to the security issues associated with same without knowing more.
The other possibility is that you are using the 'a' mode, but the file does not already exist. If you are not certain the file exists when the command is executed, you may try 'a+' as that will create the file if one does not already exist.
Does that work?
Related
I have a python script that reads and writes to files that are located relative to it, in directories above and beside it. When I run my script via Cygwin using
python script.py
The program works perfectly. However, when I run it by navigating through the windows GUI to my file and double clicking, I get a blank cmd prompt and then my program runs fine until I reach the point where I need to access the other files, at which point it fails and gives me this message in the cmd prompt that opens itself:
../FFPRM.TXT
../2025510296/FFPRM_000.TXT
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\rbanks\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:\Users\rbanks\Desktop\TSAC\EXECUTABLE\T-SAC_GUI.py", line 705, in run_exe
invalid_entry, output_text = self.apply()
File "C:\Users\rbanks\Desktop\TSAC\EXECUTABLE\T-SAC_GUI.py", line 694, in apply
p = subprocess.Popen(['cp', output_file_path, output_file_path_id])
File "C:\Users\rbanks\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 950, in __init__
restore_signals, start_new_session)
File "C:\Users\rbanks\AppData\Local\Programs\Python\Python35-32\lib\subprocess.py", line 1220, in _execute_child startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
I am deploying this script as well as the directory structure as a zip for users to be able to unzip and use anywhere on their PC, so it is important for me to be able to run it with a simple double click and my relative file paths.
My first thought was the cmd prompt that was opening and executing my script was in a different environment, but when I run:
cd
pause
in a .cmd script, I get:
C:\Users\rbanks\Desktop\TSAC\EXECUTABLE>pause
Which is the correct location.
I am not having any luck with Google, I assume because I can't seem to construct a sufficient search query. Could someone point me in the right direction please?
[edit] the other answer is correct(at least i suspect) but i will leave this here in the hopes that it helps the op in the future with path problems ... and doing something like this is just generally good practice
use
BASEPATH = os.path.abspath(os.path.dirname(__file__))
at the top of your script
the later
txt_file = os.path.join(BASEPATH,"my_file.txt")
or even
txt_file = os.path.join(BASEPATH,"..","my_file.txt")
this gives you the benefit of being able to do things like
if not os.path.exists(txt_file):
print "Cannot find file: %r"%txt_file
which will likely give you a better idea about what your problem might actually be (if its simply path related at least)
The problem is not the current directory. It is correct when double clicking on the icon
The problem is: Cygwin commands are not in the windows path
You are using python, so don't run simple copy commands like this, which make your script non-portable and subject to variations, requiring installation of cygwin, etc...
p = subprocess.Popen(['cp', output_file_path, output_file_path_id])
can be replaced by
import shutil
shutil.copyfile(output_file_path, output_file_path_id)
shutil module complements os module for file manipulation functions that aren't native in the operating system.
now you have a 100% pythonic solution, native, which will throw exceptions if cannot read/write files, so fully integrated in the rest of your program.
Before running an external command from Python make sure that no python way exists. There are so many useful modules out there.
Other examples of how to avoid running basic commands from python (of course if you need to run a C compilation it's different!):
zipfile package: much better than running zip.exe
gzip package: can open gzipped files natively from python
os.listdir() instead of parsing the output of cmd /c dir /B
os.remove() instead of calling rm or del
etc... python rules!
I'm fairly new to python. Some googling has got me to this module https://pypi.python.org/pypi/python-crontab. I've setup my env and installed python-crontab==1.9.3. But I keep getting errors. What am I doing wrong? Any help would be greatly appreciate. I'm trying to use examples but they don't seem to be working for me.
What I would like to do is the following:
add a cron job to the cron tab
Terminal Error Output:
Traceback (most recent call last):
File "test5.py", line 5, in <module>
users_cron = CronTab(user='testuser')
File "/Users/testuser/Desktop/sample1/prj-env/lib/python2.7/site-packages/crontab.py", line 187, in __init__
self.read(tabfile)
File "/Users/testuser/Desktop/sample1/prj-env/lib/python2.7/site-packages/crontab.py", line 231, in read
raise IOError("Read crontab %s: %s" % (self.user, err))
IOError: Read crontab testuser: crontab: must be privileged to use -u
users_cron = CronTab(user='testuser')
It appears like you are trying to create a cronjob for the user 'testuser'.
IOError: Read crontab testuser: crontab: must be privileged to use -u
The error is telling you that you need to be a privileged user to be able to do that. Try running your script with 'sudo':
sudo python my_python_script.py
Reference
You're trying to access a specific user's crontab, you can't do that on the base system (which is what the python module is trying to use) without root access. If you want to get your own crontab do the following:
users_cron = CronTab(user=True)
You can also use plan which is an easier way to write cron job for crontab from python:
from plan import Plan
cron = Plan()
cron.command('ls /tmp', every='1.day', at='12:00')
cron.command('pwd', every='2.month')
cron.command('date', every='weekend')
if __name__ == '__main__':
cron.run()
See more in the docs
I'm trying to run wlst script form .py file but it can not be done
Content of .py file :
connect('weblogic','weblogic','t3://localhost:8001')
sca_undeployComposite('http://localhost:8001','Hello','1.0','user='weblogic',partition='myPartition')
sca_deletePartition('myPartition')
sca_createPartition('myPartition')
sca_deployComposite('http://localhost:8001','C:\WLST\Test\Application.zip',user='weblogic',configplan='myPlan.xml', partition='myPartition')
exit()
when i run cmd file to execute script, Only connect() method is execute success. any command bellow it can not be execute. And error message appear: Problem invoking WLST - Traceback (innermost last): File "c:\WLS\script\filname.py", line 2, in ?
Name Error: sca_undeployComposite
Please help me to resolve it. Thanks !
The commands after the connect() line which are not regular WLST commands. They requires sca related libraries into CLASSPATH. if you look into your wlst.cmd or .sh file that is actually calling the environment setup file that could be setWLSEnv.sh/.cmd. If you run that from where you are having the this python script. That script will work, it is simple java CLASSPATH funda nothing else!
Probably you might be running wlst.cmd after navigating to the common bin folder like
cd /oracle/fmwhome/Oracle_SOA1/common/bin/.
instead you can run in your script like this
C:\WLS\script\>/oracle/fmwhome/Oracle_SOA1/common/bin/wlst.cmd filename.py
or
C:\WLS\script\>/oracle/fmwhome/Oracle_SOA1/common/bin/setWLSEnv.cmd
C:\WLS\script\>java weblogic.WLST filename.py
You can also refer for more sca related scripting: WLSTByExamples
Im running a solaris server which uses supervisor to monitor some Python applications.
Previously, I could run the command:
paster serve /opt/pyapps/menuadmin/prod.ini
from any directory on the server. There were some recent issues and the /opt folder was restored from a previous backup. This folder contained all of the applications including supervisor.
Now we are facing issues where supervisor will not start the applications because of "version conflicts" in Pylons.
This is where it gets weird and it makes no sense why these errors would occur.
If I run the paster command from outside of the program directory, it will throw the version conflict error. eg:
cd /
paster serve /opt/pyapps/menuadmin/prod.ini
Traceback (most recent call last):
File "/opt/csw/bin/paster", line 8, in <module>
load_entry_point('PasteScript==1.7.5', 'console_scripts', 'paster')()
File "/opt/csw/lib/python2.6/site-packages/PasteScript-1.7.5-py2.6.egg/paste/script/command.py", line 93, in run
commands = get_commands()
File "/opt/csw/lib/python2.6/site-packages/PasteScript-1.7.5-py2.6.egg/paste/script/command.py", line 135, in get_commands
plugins = pluginlib.resolve_plugins(plugins)
File "/opt/csw/lib/python2.6/site-packages/PasteScript-1.7.5-py2.6.egg/paste/script/pluginlib.py", line 82, in resolve_plugins
pkg_resources.require(plugin)
File "/opt/csw/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/pkg_resources.py", line 626, in require
File "/opt/csw/lib/python2.6/site-packages/setuptools-0.6c9-py2.6.egg/pkg_resources.py", line 528, in resolve
pkg_resources.VersionConflict: (Pylons 0.9.7 (/opt/csw/lib/python2.6/site-packages/Pylons-0.9.7-py2.6.egg), Requirement.parse('Pylons>=0.10'))
But if I run the command from inside the program directory, it will run fine. eg:
cd /opt/pyapps/menuadmin/
paster serve /opt/pyapps/menuadmin/prod.ini
Starting server in PID 29902.
serving on http://127.0.0.1:3002
I absolutely cannot get my head around why this would happen!
Any thoughts or comments at all are appreciated!!!!
Based upon what you have said it seems you are running two different version of paster. The first version is running the older Pylons package 0.9.7, whilst the second has the more up to date version that meets or exceeds your app's requirements.
What I would do is first check which version of paster you are running. From outside of the project just run:
which paster
Then run the same command again within the project directory and compare the results. I suspect that you will find that the paths differ. If that is the case then all you need to do is update the version of pylons for the first version, which I'm guessing is the global install.
However, as others have commented it would be better to run apps within virtualenv, especially if as you seem to indicate you have multiple virtualenv and thus multiple projects. Trust me when I say it will save you from loads of headaches later on, from someone that didn't do this originally.
I am trying to run a python script which uses a binary file (xFiles.bin.addr_patched) created by a postlinker. However, I am getting this error.
File "abc.py", line 74, in ParseCmd
shutil.copy(gOptions.inputX, gWorkingXFile)
File "/usr/lib/python2.6/shutil.py", line 89, in copy
copymode(src, dst)
File "/usr/lib/python2.6/shutil.py", line 66, in copymode
os.chmod(dst, mode)
OSError: [Errno 1] Operation not permitted: 'myPath/xFiles.bin.addr_patched'
When I checked the permissions of this xFiles.bin, by ls-l, it shows that
-rwxrwxrwx 1 nobody nogroup
I presume the error is because this file was created by some other application, the python script I am running does not have access to it. Since I am beginner wrt ubuntu, I don't really know how to fix it. Any suggestions on how to fix this?
SOLVED:
As one of the answers Suggested : chown username:groupname file name fixes this issue
You could try (from the command line, but I'm sure there's a syntax in python):
sudo chown your_username:your_groupname filename
Note: The group is usually just your username.
I feel like there's something wrong with those permissions though. Read Write Execute for everyone seems to be off. How was this file created? How did it get to be created by the user nobody?
Python code to change the permission:
from getpwnam import pwd
from getgrnam import grp
import os
uid = getpwnam("YOUR_USERNAME")[2]
gid = grp.getgrnam("YOUR_GROUPNAME")[2]
os.chown("myPath/xFiles.bin.addr_patched", uid, gid)
Run the script with sudo and you're done.
I had this problem when running a python script on my mac (10.14 Mojave) trying to access /Users/xxx/Pictures/Photos Library.photoslibrary.
The full solution can be found in http://osxdaily.com/2018/10/09/fix-operation-not-permitted-terminal-error-macos/
Summary:
Go to System Preferences > Security & Privacy > Privacy > Full Disk Access and add your IDE or python interpreter to the list.
My guess is that you should be looking at the permissions for myPath folder instead. Seems like you can't write to it, hence the problem. Try ls -l myPath/.. and see the permissions for myPath. If that's the problem, change the permissions on the folder with chmod.
P.S. Also, see Google top result on Linux file permissions.