Error when using os.stat - Python - python

Solved: Adding an os.chdir(myArg) resolved the issue.
I'm getting an error when trying to run the following code on anything other than my home directory or files/direcs that I own.
FileNotFoundError: [Errno 2] No such file or directory:
I created a file in root and changed ownership on the file to pi:pi (user running the script). If I specify that file directly, it works, however if I run the script on "/", it will not read that or any other file/direc. I also created a directory /tempdir_delete/ and changed ownership to pi:pi.. If I run the script specifically on "/tempdir_delete/*", it works, but if I leave off the * it fails.
Why does it fail on all except /home/pi/ or files that I explicitly specify and own? It's running the stat as user pi, which is granted by sudo to perform the stat. Also, why do I have to specify the file that I own explicitly? Shouldn't it see that file in root and work because I own it?
import os
import re
import sys
import pwd
myReg = re.compile(r'^\.')
myUID = os.getuid()
myArg = sys.argv[1]
print(os.getuid())
print(pwd.getpwuid(int(myUID)))
print(myArg)
def getsize(direct):
if os.path.isfile(direct) == True:
statinfo = os.stat(myArg)
print(str(statinfo.st_size))
else:
for i in os.listdir(direct):
try:
statinfo = os.stat(i)
if myReg.search(i):
continue
else:
print(i + ' Size: ' + str(statinfo.st_size))
except:
print('Exception occurred, can't read.')
continue
getsize(myArg)

Solved. Adding an os.chdir(myArg) worked to resolve the issue.

Related

How do I specify the path to the library to run a script from another script?

I need to check the change of one parameter, if it has changed - I need to restart the script.
code:
import subprocess, os.path, time
from engine.db_manager import DbManager
DB = DbManager(os.path.abspath(os.path.join('../webserver/db.sqlite3')))
tmbot = None
telegram_config = DB.get_config('telegram')
old_telegram_token = ''
vkbot = None
vk_config = DB.get_config('vk')
old_vk_token = ''
while True:
telegram_config = DB.get_config('telegram')
if old_telegram_token != telegram_config['token']:
if vkbot != None:
tmbot.terminate()
tmbot = subprocess.Popen(['python', 'tm/tm_bot.py'])
old_telegram_token = telegram_config['token']
print('telegram token was updated')
vk_config = DB.get_config('vk')
if old_vk_token != vk_config['token']:
if vkbot != None:
vkbot.terminate()
vkbot = subprocess.Popen(['python', 'vk/vk_bot.py'])
old_vk_token = vk_config['token']
print('vk token was updated')
time.sleep(30)
I get errors:
enter image description here
While there might be subtle differences between unix and windows, the straight-up answer is: you can use PYTHONPATH environment variable to let python know where to look for libraries.
However, if you use venv, I'd recommend activating it first, or calling the relevant binary instead of setting the environment variable.
Consider this scenario: you have a venv at /tmp/so_demo/venv, and you try to run this file:
$ cat /tmp/so_demo/myscript.py
import requests
print("great success!")
Running the system python interpreter will not find the requests module, and will yield the following error:
$ python3 /tmp/so_demo/myscript.py
Traceback (most recent call last):
File "/tmp/so_demo/myscript.py", line 1, in <module>
import requests
ModuleNotFoundError: No module named 'requests'
As I have installed requests in the venv, if I provide the path to python, it will know where to look:
$ PYTHONPATH='/tmp/so_demo/venv/lib/python3.8/site-packages/' python3 /tmp/so_demo/myscript.py
great success!
but using the binary inside the venv is better, as you don't need to be familiar with the internal venv directory paths, and is much more portable (notice that the path I provided earlier depicts the minor version):
$ /tmp/so_demo/venv/bin/python /tmp/so_demo/myscript.py
great success!

Issue with NameError

So I am fairly new with coding in Python and in general and I am trying to write a program that will backup files in a giving folder. However, I continue to get a "NameError: name 'src' is not defined. I see some other questions similar about this error but none have yet to make me understand what I am doing wrong or why I get this error. As far as I understand it I am defining 'src' in the code below. Any help would be greatly appreciated.
ERROR:
File "/home/student/PycharmProjects/Lab1.py/Lab5.5.py", line 1, in processing
backup(src, dest)
NameError: name 'src' is not defined
def backup(src, dest):
#Checking if src and dest directories exist
sourceFilePath = input('Enter folder path to be backed up')
destFilePath = input('Please choose where you want to place the backup')
#found = true
for directory in [src, dest]:
if not isdir(directory):
print(f'could not find {directory}')
found = False
if not found:
exit(1)
#for each file in src
for sourceFileName in listdir(src):
#computing file paths
sourceFilePath = path.join(src, sourceFileName)
destFilePath = path.join(dest, sourceFileName)
#backing up file
copy2(sourceFilePath, destFilePath)
#entry point
if __name__=='__main__':
#validating length of command line arguments
if len(argv) != 3:
print(f'Usage: {argv[0]} SRC DEST')
exit(1)
#performing backup
backup(argv[1], argv[2])
#logging status message
print('Backup succesful!')
why are you prompting the user for src and dest path though you already pass them as command args? The issue probably came from the fact you didn't provide the src arg while running the script. Things like
python script.py srcpath dstpath

finding file with unicode characters using Path.glob in python3 on OSX

How do I find a filename starting with "dec2💜file" that has an extension on OSX?
In my case, I have only one .ppt file in the Documents directory. So, the result should be:
dec2💜file.ppt
Here is the code:
my_pathname='Documents'
my_filename='dec2💜file'
my_glob = "{c}.{ext}".format(c=my_filename, ext='*')
try:
my_filename = str(list(pathlib.Path(my_pathname).glob(my_glob))[0])
except Exception as ex:
print("Error - {d}/{f} - {e}".format(d=my_pathname, f=my_glob, e=str(ex)))
exit(1)
print("Found it - {f}".format(f=my_filename))
Current result:
ERROR - Documents/dec2💜file.* - list index out of range
How do I get it to find the file and print:
Found it - dec2💜file.ppt
After creating a folder called test, and a file inside it called dec2💜file.txt, I ran this:
import pathlib
my_pathname = 'test'
my_filename = 'dec2💜file'
my_glob = "{c}.{ext}".format(c=my_filename, ext='*')
try:
my_filename = str(list(pathlib.Path(my_pathname).glob(my_glob))[0])
except Exception as ex:
print("Error - {d}/{f} - {e}".format(d=my_pathname, f=my_glob, e=str(ex)))
exit(1)
print("Found it - {f}".format(f=my_filename))
And got:
Found it - test\dec2💜file.txt
So, I can only conclude there is no folder called Documents inside the working directory where your script runs. Try replacing my_pathname with a full path name, or ensure your script runs in the parent directory of Documents.
You can do this by either changing the working directory of the script from your IDE or on the command line, or by using os.chdir or something similar to change directory before the relevant part of the script.

Stop python program from closing when a directory is not found

Im creating a DOS clone with python and I have a command cd which allows you to change directory. The only problem is that if you misspell or type a non-existent directory, the program closes with a traceback error. Im basically looking for it not to completely close the program but instead print a statement like 'requested_directory' Is not a directory! and allow you to type in a different directory.
Ive tried a couple things, mainly error handling, but to no prevail. Im assuming that im still not quite understanding error handling or using it incorrectly.
Any help is much appreciated.
This is the code im using to change directories (elif because i have many more commands. cmd is a raw input.)
elif 'cd' in cmd:
desired_directory = cmd.split(' ')[1]
if desired_directory == "..":
os.chdir('..')
else:
os.chdir(desired_directory)
This is the output when an incorrect directory is typed in
Traceback (most recent call last):
File "/Users/jrosmac/PycharmProjects/untitled/JDOS/SYS64/jdosos.py", line 47, in <module>
os.chdir(desired_directory)
OSError: [Errno 2] No such file or directory: 'raw_input goes here'
I believe you need to handle the error.
try:
os.chdir(desired_directory)
except OSError as e:
print e.args[0]
Use exception handing:
try:
os.chdir(target)
except OSError as e:
# handle the failure of the chdir call

import python module when launching from VBA

It is the first time I write as I really didn't find any solution to my issue.
I want to allow my user to launch some Python program from Excel.
So i have this VBA code at some point:
lg_ErrorCode = wsh.Run(str_PythonPath & " " & str_PythonArg, 1, bl_StopVBwhilePython)
If lg_ErrorCode <> 0 Then
MsgBox "Couldn't run python script! " _
+ vbCrLf + CStr(lg_ErrorCode)
Run_Python = False
End If
str_PythonPath = "C:\Python34\python.exe C:\Users\XXXX\Documents\4_Python\Scan_FTP\test.py"
str_PythonArg = "arg1 arg2"
After multiple testing, the row in error in Python is when I try to import another module (I precise that this VBA code is working without the below row in Python):
import fct_Ftp as ftp
The architecture of the module is as follow:
4_Python
-folder: Scan_FTP
- file: test.py (The one launch from VBA)
-file: fct_Ftp.py
(For information, I change the architecture of the file, and try to copy the file at some other position just to test without success)
The import has no problem when I launch Test.py directly with:
import sys, os
sys.path.append('../')
But from VBA, this import is not working.
So I figured out this more generic solution, that dont work as well from Excel/VBA
import sys, os
def m_importingFunction():
str_absPath = os.path.abspath('')
str_absPathDad = os.path.dirname(str_absPath)
l_absPathSons = [os.path.abspath(x[0]) for x in os.walk('.')]
l_Dir = l_absPathSons + [str_absPathDad]
l_DirPy = [Dir for Dir in l_Dir if 'Python' in Dir]
for Dir in l_DirPy:
sys.path.append(Dir)
print(Dir)
m_importingFunction()
try:
import fct_Ftp as ftp
# ftp = __import__ ("fct_Ftp")
write += 'YAAAA' # write a file YAAAA from Python
except:
write += 'NOOOOOO' # write a file NOOOOO from VBA
f= open(write + ".txt","w+")
f.close()
Can you please help me as it is a very tricky questions ?
Many thanks to you guys.
You are able to start your program from the command line?
Why not create a batch file with excel which you then start in a shell?

Categories

Resources