File system Python - import not working - python

I have a Python script in a file stored in a Folder MyFolder. Tree structure for the file system is the following
MyFolder
- Image
- scipt_image.py
- script.py
- script_test.py
I want to use scripts in Image, scipt_image.py, in script script.py. To include this script_image.py, I use this :
import os, sys
DATA_DIR = os.path.abspath(os.path.join(os.getcwd(), 'Image'))
sys.path.append(DATA_DIR)
Then, i import script_image.py, with
import scipt_image
From errors at compilation, this seems not be working. However, problem may come from something else. Does this sounds correct ?
thanks

Is there a specific reason you don't simply use the Image folder as a python package and import the file directly without messing with sys.path?
I would simply turn Image into a python package (create an empty file named __init__.py in Image) and then import script_image like this:
from Image import script_image

Related

PYTHON AND BATCH SCRIPT: Run file if it exists and create if it doesn't

Full Disclaimer: I DO NOT KNOW PYTHON.
Hi Guys,
I have made an AutoHotKey Script for my volume keys. I would like to create a batch file which runs a python file (so if I change computers, I can easily create this scripts) which would do the following
Check if volume_keys.ahk exists in the D Drive
If it exists, run that;
If it doesn't exist, then create a file named volume_keys.ahk and add my script to it.
My script is:
^!NumpadMult::Send {Volume_Mute}
^!NumpadAdd::Send {Volume_Up}
^!NumpadSub::Send {Volume_Down}
I know how to code the .bat file and just need help for the python point-of-view, but I request the community to check it:
#ECHO OFF
ECHO This script will run an AHK Script. If you want to stop this process from happening, then cross this window off.If you want to continye:
pause
cd d:
D:\run_volume_keys_ahk_script.py
I really appreciate any help by the community.
Thanks in advance
You can use the os library for this. Here's what the python program would look like.
import os
if os.path.isfile('D:\\volume_keys.ahk'): # check if it exists
os.system('D:\\volume_keys.ahk') # execute it
else:
with open('D:\\volume_keys.ahk', 'w') as f: # open it in w (write) mode
f.write('^!NumpadMult::Send {Volume_Mute} \
^!NumpadAdd::Send {Volume_Up} \
^!NumpadSub::Send {Volume_Down}') # Write to file
os.system('D:\\volume_keys.ahk') # execute
To activate the ahk script, you might want to use the subprocess module, of which I took the example from here
import subprocess
subprocess.call(["path/to/ahk.exe", "script.ahk"])
Note that you'll have to find the ahk executable on a computer before you can use the script, maybe you want to automatically check that too.
You can set the path you want to check for scripts in one string, and then add the filenames of your scripts as strings to a list. You can use listdir() from the os module to see any files and directories at a given path, then iterate over your scriptnames and check if it exists in that list of files. If it does, run it.
In this example I copy-pasted your script into a string as value for the key 'scriptname' in a dictionary, so that python can actually create the script file. This isn't really a neat way to do it though, you might want to have your scripts prepared in a directory next to your python script and copy them from there. See an example of how here
from os import listdir
from os.path import isfile, join
CHECK_PATH = "D:"
AHK_EXECUTABLE_PATH = "path/to/ahk.exe"
SCRIPTS_TO_CHECK = {'script1.ahk':"""^!NumpadMult::Send {Volume_Mute}
^!NumpadAdd::Send {Volume_Up}
^!NumpadSub::Send {Volume_Down} """, 'script2.ahk':" some other script here"}
files_to_check = set(listdir(CHECK_PATH)) # using a set for fast lookup later
for scriptname, script in SCRIPTS_TO_CHECK.items():
if not scriptname in files_to_check:
print(f"script {scriptname} not found, creating it.")
with open(scriptname, 'w') as file:
file.write(script)
# else
subprocess.call(AHK_EXECUTABLE_PATH, scriptname)

Importing python files in another python file [duplicate]

This question already has answers here:
How do I import other Python files?
(23 answers)
Closed 2 years ago.
I have a folder of this file structure:
Desktop
tech_comp
googledash.csv
viz.py
sql_load.py
company_AL
__init__.py
functionloads.py
decisionplans.py
niches.py
actions.py
I am working with VScode in the following path as described above: C:\Users\username\Desktop\tech_comp\company_AL
I have written a bunch of list in the decisionplans.py now I am trying to load it in the actions.py I am working with. Here is what I did.
from company_AL import decisionplans
It does not show errors in the compiler but when I run I get the following.
ModuleNotFoundError: No module named 'company_AL'
I do not intend to publish it as online as this is a private project, please how do I handle this?
Thanks in advance
You have many solutions to solve your problem :
1. Add compagn_AL folder to your PYTHON_PATH
It depends of your OS but there is tutorials that explians better than me
2. Change the PATH for your script
import sys
sys.path.append('../') # or "C:\Users\username\Desktop\tech_comp\"
and then
from compagny_AL import decisionplans
3. Import it directly (not recommended)
You can just
import decisinplans
I think you just need to do import decisionplans or from .company_AL import decisionplans because you are already in the company_AL.

how to modify txt file properties with python

I am trying to make a python program that creates and writes in a txt file.
the program works, but I want it to cross the "hidden" thing in the txt file's properties, so that the txt can't be seen without using the python program I made. I have no clues how to do that, please understand I am a beginner in python.
I'm not 100% sure but I don't think you can do this in Python. I'd suggest finding a simple Visual Basic script and running it from your Python file.
Assuming you mean the file-properties, where you can set a file as "hidden". Like in Windows as seen in screenshot below:
Use operating-system's command-line from Python
For example in Windows command-line attrib +h Secret_File.txt to hide a file in CMD.
import subprocess
subprocess.run(["attrib", "+h", "Secret_File.txt"])
See also:
How to execute a program or call a system command?
Directly call OS functions (Windows)
import ctypes
path = "my_hidden_file.txt"
ctypes.windll.kernel32.SetFileAttributesW(path, 2)
See also:
Hide Folders/ File with Python
Rename the file (Linux)
import os
filename = "my_hidden_file.txt"
os.rename(filename, '.'+filename) # the prefix dot means hidden in Linux
See also:
How to rename a file using Python

Python3 import file from directory starting with number

I tried the answers in this question to no avail so I thought it'd be worth a separate question. The directory layout is as follows:
aale/
2/
2.py
__init__.py
3/
3.py
__init__.py
__init__.py
The names are unfortunately unable to change (this is the layout given to us for a HW problem). I am trying to import 2 from 3 but it doesn't seem to be working. I tried using importlib as:
two = importlib.import_module('2.2') as well as
two = importlib.import_module('2')
which didn't work also (gave a ModuleNotFoundError: No module named '2' error). Any help / other methods would be appreciated. I am using Python 3.6.
Assuming your script is in the aale directory, you will need to do your import like:
two = importlib.import_module('aale.2.2')
You can use __import__, i.e.:
two = __import__("2.2") # or __import__("aale.2.2")
three = __import__("3.3") # or __import__("aale.3.3")
Equivalent to:
import 2.2 as two
import 3.3 as three
which isn't possible.
Notes:
According to PEP 8 styling guide:
Package and Module Names should have short, all-lowercase names. Underscores can be used in the module name
if it improves
readability.
I've tested the imports using the same folder structure as in your
question and no errors were shown.
References:
https://stackoverflow.com/a/16644280/797495
In python, how to import filename starts with a number
PEP 8 -- Style Guide for Python Code
You can use pathlib
It is basic:
from pathlib import Path
BASE_LOCATION = Path(__file__).parent
(You can add .parent to get to the folder above and so on.)
Edit
If this doesn't help you, you can try import weirdimport.
You can read more about this here.
Hope this helps!

Make cx_Freeze main.py permanently being able to use numpy module

I am using the cx_Freeze script located in the Python36/Scripts folder on a regular basis to convert python files into executables and it works fine. However it seems to still not being able to convert numpy so I am trying to make it work by adding an option into the main.py which is used by the cx_Freeze script described above. This main.py is located in the site-packages/cx_Freeze folder.
Thomas K. provided a solution here: Creating cx_Freeze exe with Numpy for Python
by adding this line to the options:
options = {"build_exe": {"packages": ["numpy.lib.format"]}}
Is it possible to add this line to the main.py in the options section? If so how would I do that?
Your help is much appreciated.
If I understand correctly what you like to do, you could try to add the following two lines to the file site-packages/cx_Freeze/freezer.py
## -127,6 +127,8 ## class Freezer(object):
self.includes = list(includes)
self.excludes = list(excludes)
self.packages = list(packages)
+ if 'numpy.lib.format' not in self.packages:
+ self.packages.append('numpy.lib.format')
self.namespacePackages = list(namespacePackages)
self.replacePaths = list(replacePaths)
self.compress = compress

Categories