How can I open a file with its correct program (e.g. ".blend" with Blender and ".webloc" with Chrome) inside a Python program? - python-3.x

I'm working with IDLE on Mac and I'm trying to make a small program that opens a random file from a folder (it is actually a test for a bigger project). In the folder, I have many types of files like ".blend", ".m4a", ".py" and ".webloc" but I expect to have even more in the future. I would like my code to open a random one with their respective program (Blender, QuickTime Player, IDLE, Chrome...) but so far I have not found any way to do it. Is it possible? The most I've been able to do is open Google Chrome from my Windows computer. It doesn't work on my Mac (maybe because it is .app instead of .exe?) and I can only open programs, but not files. Here's the code I used for that:
import subprocess
subprocess.Popen(['C:\Program Files (x86)\Google\Chrome\Application\\chrome.exe', '-new-tab'])
When I enter that on Mac (but with the correct file path for Mac):
import subprocess
subprocess.Popen(['/Applications/Google Chrome.app', '-new-tab'])
It gives me this error (could it be because the file path is written incorrectly? I copied it with right-click on the Chrome file and clicking "copy as path"):
>>>
=============== RESTART: /Users/jaimewalter/Desktop/Test/Test3.py ==============
Traceback (most recent call last):
File "/Users/jaimewalter/Desktop/Test/Test3.py", line 3, in <module>
subprocess.Popen(['/Applications/Google Chrome.app', '-new-tab'])
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/subprocess.py", line 854, in __init__
self._execute_child(args, executable, preexec_fn, close_fds,
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/subprocess.py", line 1702, in _execute_child
raise child_exception_type(errno_num, err_msg, err_filename)
PermissionError: [Errno 13] Permission denied: '/Applications/Google Chrome.app'
>>>
And here's my code for the random file selector:
import random
files = ["Test1.blend", "Test2.m4a", "Test3.py", "Test4.webloc"]
open_this = random.choice (files)
print(open_this)
if open_this == "Test1.blend":
print("Opening Test1.blend")
#now it should open Test1.blend on a new Blender window (/Users/jaimewalter/Desktop/Test/Test1.blend)
elif open_this == "Test2.m4a":
print("Opening Test2.m4a")
#now it should open Test2.m4a on a new QuickTime Player window (/Users/jaimewalter/Desktop/Test/Test2.m4a)
elif open_this == "Test3.py":
print("Opening Test3.py")
#now it should open Test3.py on a new IDLE window or preferably runs the code inside directly it if that's possible (/Users/jaimewalter/Desktop/Test/Test3.py)
elif open_this == "Test4.webloc":
print("Opening Test4.webloc")
#now it should open Test4.webloc on a new Chrome or Safari window (/Users/jaimewalter/Desktop/Test/Test4.webloc)
What should I use to open the files inside the code? Thanks in advance

I already solved it. I used
import subprocess
subprocess.call(["open", "Test1.blend"])
I think with Linux it's xdg-open

Related

UndetectedChromedriver Extension Issue

I can't use extensions on UndetectedChromedriver PYPI Package (Python). If I use it with normal selenium its works, but not with this package. I tried to install extensions directly from webstore, but Chrome Webstore Alert is not an Alert to handle with selenium is a Window Event, so we need to use AutoIT, Pyautogui, etc... To handle that.
The only thing is working is loading profiles, but... I'm working for multiprocess windows, is working, but I need to create houndred of windows and then delete them. And I can't clone profiles, because UndetectedChromedriver doesn't work, i need to create manually.
Finally i tried with Google Chrome Enterprise Bundle, then I used Extensions policy to install forced the extension for all profiles. And yes, is working, but if I enabled that, selenium, doesn't work properly.
The error traceback log is:
Exception in thread Thread-2:
Traceback (most recent call last):
File "C:\Users\andre\anaconda3\envs\selenium-env\lib\threading.py", line 950, in _bootstrap_inner
self.run()
File "C:\Users\andre\anaconda3\envs\selenium-env\lib\threading.py", line 888, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\andre\OneDrive\Documentos\(A1)_Inicio\(A2)_CyberEspacio\LAB\(A1)_Programador123\(A1)_Programming_(Section)\VSCode Snippets\python\selenium\app.py", line 72, in test
seleniumCaptchaSolver.reCaptchaServiceLogin(apiKey='MYAPIKEY', solverType = SeleniumCaptchaSolverType().Capmonster)
File "C:\Users\andre\OneDrive\Documentos\(A1)_Inicio\(A2)_CyberEspacio\LAB\(A1)_Programador123\(A1)_Programming_(Section)\VSCode Snippets\python\selenium\modules\seleniumCaptchaSolver.py", line 103, in reCaptchaServiceLogin
self.__driver.get('chrome-extension://pabjfbciaedomjjfelfafejkppknjleh/popup.html')
File "C:\Users\andre\anaconda3\envs\selenium-env\lib\site-packages\undetected_chromedriver\__init__.py", line 535, in get
return super().get(url)
File "C:\Users\andre\anaconda3\envs\selenium-env\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 447, in get
self.execute(Command.GET, {'url': url})
File "C:\Users\andre\anaconda3\envs\selenium-env\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 435, in execute
self.error_handler.check_response(response)
File "C:\Users\andre\anaconda3\envs\selenium-env\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.WebDriverException: Message: unknown error: cannot determine loading status
from disconnected: received Inspector.detached event
(Session info: chrome=103.0.5060.134)
This happen only when chrome-extension://pabjfbciaedomjjfelfafejkppknjleh/popup.html is opened to login (Send APi Key). I can login etc... But when Policy is Activated I can't because of that issue.
Anyone here know how to fix that or properly use extensions in UndetctedChromedriver?
Note: This error only happens if i load chrome-extension://pabjfbciaedomjjfelfafejkppknjleh/popup.html link, others links works.
I found this solution:
import undetected_chromedriver as uc
import os
working_dir = os.getcwd()
# Im using proxy extension
proxy_plugin = f'{working_dir}/proxy_plugin'
options = uc.ChromeOptions()
options.add_argument(f'--load-extension={proxy_plugin}')
# {proxy_plugin} path to extension folder, I tried to import .zip file
# and this doesnt working, maybe you can try import .crx file
# Also, I use extensions.ui.developer_mode
options.add_experimental_option('prefs', { 'extensions.ui.developer_mode': True })
driver = uc.Chrome(options = options)
extensions.ui.developer_mode
Yet, I seen this pages:
Load unpacked Chrome extension programmatically
Installing extension into V2

Embedded Python: How to Compile Script from Memory (Not a File) That Requires "Pickle"

My app hosts embedded Python so that users can create and run scripts using the Python 3.9 framework for macOS. The scripts are not stored as files on disk, but in the my app's memory.
In general, I am successfully compiling and running these scripts from memory using Py_CompileString/PyImport_ExecCodeModule
However, I get a "pickle" error when attempting to run a script that uses the multiprocessing module.
I created a command line program to replicate the problem. Upon trying to execute the following code as a string (with proper newlines, etc.) using PyRun_SimpleString()
from multiprocessing import Process
import sys
def foo(name):
print('executing foo', name)
def python_main():
# set the executable to path to python, not this command line program
sys.executable = '/Library/Frameworks/Python.framework/Versions/3.9/Resources/Python.app/Contents/MacOS/Python'
# set sys.argv[0] to '__main__' since it will be empty otherwise
sys.argv[0] = '__main__'
print('creating process')
p = Process(target=foo, args=('Hi Bob!',))
p.start()
p.join()
print('process complete - exit code', p.exitcode)
if __name__ == '__main__':
python_main()
I receive the following output:
creating process
starting process
joining process
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/spawn.py", line 116, in spawn_main
exitcode = _main(fd, parent_sentinel)
File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/multiprocessing/spawn.py", line 126, in _main
self = reduction.pickle.load(from_parent)
AttributeError: Cant get attribute 'foo' on <module '__main__' (built-in)>
process complete - exit code 1
python_main complete
If I run the same code from an actual file called mp.py as follows, then it executes successfully.
PyRun_SimpleString("import mp; mp.python_main()");
Is there something I must do to allow my in-memory script to be pickled as it is when the file is on disk?
P.S. It is worth mention that when I compile the code using Py_CompileString/PyImport_ExecCodeModule, the code looks something like this:
codeObj = Py_CompileString(inScript.c_str(), "mp.py", Py_file_input);
moduleObj = PyImport_ExecCodeModule("mp", codeObj);
so the code does have an "imginary" file name (imaginary because the script text is in memory, not on disk) and a real module name.

FileNotFoundError while using crontab to run Python script

I'm totally lost here. I'm trying to create a scheduler to run python script on my Mac, but I'm getting the following error:
Traceback (most recent call last):
File "/Users/Root/Desktop/Project/Data/script.py", line 148, in <module>
run(
File "/Users/Root/Desktop/Project/Data/script.py", line 121, in run
config = get_config("config")
File "/Users/Root/Desktop/Project/Data/config/__init__.py", line 3, in get_config
with open(f"config/{config_type}.json", "r") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'config/config.json'
So crontab convinces me that there is no such file or a directory, which is not true. I can run my script manually without errors.
My crontab is:
00 19 21 1-12 * /Library/Frameworks/Python.framework/Versions/3.9/bin/python3/ /Users/Root/Desktop/Project/Data/script.py >> /Users/Root/Desktop/Project/Data/cron.txt 2>&1
What am I doing wrong?
I'd be grateful for any help!
And is this possible without changing the relative path to an absolute path? I am aware of this solution
I assume crontab's cwd (Current Working Directory) is not same as where the script is stored.
this would solve your problem:
import os
script_dir = os.path.dirname(os.path.realpath(__file__))
os.chdir(script_dir)
You can get the directory where you script is by calling "os.path.dirname(os.path.realpath(file))"
if you change the current working directory "os.chdir(...dir...)" you can access you config/config.json by relative path,
Otherwise you will have to use a absolute path
Try running this and check your output file:
import os
script_dir = os.path.dirname(os.path.realpath(__file__))
print (os.getcwd())
print(script_dir)
os.chdir(script_dir)
print (os.getcwd())
Try to open with full path to the json file.

Python: FileNotFoundError: [Errno 2] No such file or directory - How to add file to the right directory

I'm new to python! Seen many issues related to this problem but can't find the right way of doing it.
I want to import a picture and change it.
My code is:
from PIL import Image, ImageFilter
import os
root_dir= os.path.dirname(os.path.abspath(r'C:\Users\User\eclipse-workspace\Practice Python CS50 2019\images\Mario.png'))
before = Image.open('Mario.png')
after=before.filter(ImageFilter.BLUR)
after.save("MarioBLUR.png")
The error I'm getting is:
Traceback (most recent call last):
File "C:\Users\User\eclipse-workspace\Practice Python CS50 2019\src\Class 6\blur.py", line 5, in
before = Image.open('Mario.png')
File "C:\Users\User\anaconda3\lib\site-packages\PIL\Image.py", line 2809, in open
fp = builtins.open(filename, "rb")
FileNotFoundError: [Errno 2] No such file or directory: 'Mario.png'
My windows location for this picture is: C:\Users\User\Downloads\Mario.png
My eclipse location is: C:\Users\User\eclipse-workspace\Practice Python\images\Mario.png
How to add this picture to the right directory to make sure I won't have this issue anymore?
You only need the directory path and not the filename in os.path.dirname, for example:
root_dir= os.path.dirname('C:/Users/User/eclipse-workspace/Practice Python CS50 2019/images/')
before = Image.open(root_dir + 'Mario.png')
should work fine

FileNotFoundError: [WinError 2] The system cannot find the file specified while loading model from s3

I have recently saved a model into s3 using joblib
model_doc is the model object
import subprocess
import joblib
save_d2v_to_s3_current_doc2vec_model(model_doc,"doc2vec_model")
def save_d2v_to_s3_current_doc2vec_model(model,fname):
model_name = fname
joblib.dump(model,model_name)
s3_base_path = 's3://sd-flikku/datalake/current_doc2vec_model'
path = s3_base_path+'/'+model_name
command = "aws s3 cp {} {}".format(model_name,path).split()
print('saving...'+model_name)
subprocess.call(command)
It was successful, but after that when i try to load the model back from s3 it gives me an error
model = load_d2v("doc2vec_model")
def load_d2v(fname):
model_name = fname
s3_base_path='s3://sd-flikku/datalake/current_doc2vec_model'
path = s3_base_path+'/'+model_name
command = "aws s3 cp {} {}".format(path,model_name).split()
print('loading...'+model_name)
subprocess.call(command)
model=joblib.load(model_name)
return model
This is the error i get:
loading...doc2vec_model
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 7, in load_d2v
File "C:\Users\prane\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 339, in call
with Popen(*popenargs, **kwargs) as p:
File "C:\Users\prane\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 800, in __init__
restore_signals, start_new_session)
File "C:\Users\prane\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 1207, in _execute_child
startupinfo)
FileNotFoundError: [WinError 2] The system cannot find the file specified
I don't even understand why it is saying File not found, this was the path i used to save the model but now i'm unable to get the model back from s3. Please help me!!
I suggest that rather than your generic print() lines, showing your intent, you should print the actual command you've composed, to verify that it makes sense upon observation.
If it does, then also try that exact same aws ... command directly, at the command prompt where you had been launching your python code, to make sure it runs that way. If it doesn't, you may get a more clear error.
Note that the error you're getting doesn't particularly look like it's coming from the aws command, of from the S3 service - which might talk about 'paths' or 'objects'. Rather, it's from the Python subprocess system & Popen' call. I think those are via your call tosubprocess.call(), but for some reason your line-of-code isn't shown. (How are you running the block of code with theload_d2v()`?)
That suggests the file that's no found might be the aws command itself. Are you sure it's installed & runnable from the exact working-directory/environment that your Python is running in, and invoking via subprocess.call()?
(BTW, if my previous answer got you over your sklearn.externals.joblib problem, it'd be good for you to mark the answer as accepted, to save other potential answerers from thinking that's still an unsolved question that's blocking you.)
try to add extension of your model file to your fname if you are confident the model file is there.
e.g. doc2vec_model.h3

Resources