Start python file in Swift - python

I want to start a pythonscript by pushing a Button in a swift macOS application. I come up with:
let process = Process()
process.launchPath = "/usr/bin/python3"
process.currentDirectoryPath = "\(NSHomeDirectory())" + "/PycharmProjects/untitled5"
process.arguments = ["myscript.py"]
process.launch()
but I get "launch path not accessible" error by executing. If I change launchPath to:
process.launchPath = "/usr/bin/python"
everything works fine, but now I getting python compiling errors because myscript is written in python3.6.0, I have to use python3 because of using a library.
When I open Finder and go to "/usr/bin/python3" it says not found, but python3 is installed, I used it in Pycharm and I'm also able to start python3 in terminal.
In terminal "python3 ~/PycharmProjects/untitled5/myscript.py" works.

On your terminal type
which python3
this will return the path that is accessed when you run python3 from the command line

Related

How to run an exe file for silent install using Admin privileges

I am trying to write a python script which would install a printer software on my machine using silent install.
The script is something like this and I run the script in a command line run as Admin-
cmd = 'PDFCreator-5_0_3-Setup.exe /COMPONENTS="program" /VERYSILENT /NORESTART'
response = subprocess.call(cmd, shell=True)
print('response:', response)
However, I would like to run this as an admin inside the script itself(as my script runs automatically as part of my code), but could not find a way yet. Help is much appreciated.
I have tried using the runAs option with Powershell, but when I use the above command with the Start-Process, I m getting syntax errors:
cmd_to_install = "& { Start-Process "pathofthefile+\PDFCreator-5_0_3-Setup.exe" -ArgumentList #("/COMPONENTS="program" /VERYSILENT /NORESTART") -Verb RunAs}"

Vscode not interactive with python. Mac M1 chip

I am on a Mac with M1 chip and I have a problem with my VScode and python. It stays stuck on the ZSH shell even when I type the command to switch to bash (chsh -s /bin/bash). Lets say I run a simple code:
import cowsay
import sys
if len(sys.argv) == 2:
cowsay.cow("Hello, " + sys.argv[1])
I am supposed to be able to type my name in the shell after my python file name and it should print the cow saying Hello, Noah.
When I do so ((base) noahhaitas#Noahs-Mac-mini ~ % python3 itunes.py Noah Haitas), this is what I get as a message in my shell:
(base) noahhaitas#Noahs-Mac-mini ~ % python3 itunes.py Noah Haitas
/Library/Frameworks/Python.framework/Versions/3.10/bin/python3: can't open file '/Users/noahhaitas/itunes.py': [Errno 2] No such file or directory
I am trying to figure out how I can switch fully to bash and have the $ in front instead of seeing the % of ZSH.
What can be done as this is frustrating and I looked everywhere online and tried pretty much every solution.
Vscode is just an editor, and the system terminal is still applied.
Use the following command in the terminal to switch bash and restart the terminal:
chsh -s /bin/bash
At the same time, you can also set manually in the vscode terminal. Take Windows as an example:
Read the docs for more details about terminal settings.
By the way, there is an error when you run the file. It seems that the python file is not run in the correct directory.

How to run bash commands from Python preferably with the os library?

I am trying to run the following python script named test.py. It contains multiple bash commands which I would like to execute in a Linux terminal (unix). This is the content of the file:
import os
os.system('echo install virtualenv')
os.system('sudo pip install virtualenv')
os.system('echo create virtual environment')
os.system('virtualenv my_virtualenvironment')
os.system('echo activate virtual environment')
os.system('source my_virtualenvironment/bin/activate')
I am running the Python script using the following in the terminal:
python3 test.py
The problem that I have is that the commands do not run the same way as they would on a Linux terminal. The output is the following error when trying to execute the last line of the Python script:
sh: 1: source: not found
The last command source my_virtualenvironment/bin/activate normally runs fine if I execute it directly in the terminal (without my Python script). Now, what does sh: 1: mean and why does it not work with my code? I would expect to get something starting with bash: .
Also I have found this solution, but I would like not to use lists for executing commands and maybe even to stick with the os library (if there is a simpler solution without os, I am also open for that):
https://stackoverflow.com/a/62355400/11535508
source is a bash built-in command, not an executable.
Use the full path to the python interpreter in your commands instead of venv activation, e.g. os.system('<venv>/bin/python ...').
The second option is to write your commands into a separate bash script and call it from python:
os.system('bash script.sh')

Gimp won't launch properly from a shell script in OSX

I'm using MacOS Mojave (v. 10.14.16, latest version with all updates) and I'm running Gimp 2.10. I made a Python plugin that works great from the command line terminal, but I can't it to work from a shell script. The plugin opens an XCF template, adds an external JPG as a new layer, positions the external JPG using x and y offsets, flattens, and then exports a new JPG that shows the external JPG in the template.
Background info:
In OSX just typing “gimp” at a terminal did not launch Gimp, so I created an alias in the .bash_profile in my home directory (/users/TimB) using the steps described here: https://mattmazur.com/2012/01/27/how-to-add-terminal-aliases-in-mac-os-x-lion/. The alias reads as follows:
alias gimp=”/Applications/GIMP-2.10.app/Contents/MacOS/gimp”
My alias works great from the command line terminal, but not from a shell script.
In my shell script just trying to execute “gimp” on a line does not launch Gimp so I believe my alias is not recognized in the script. Therefore, to launch Gimp along with my Python command line arguments I do this:
/applications/gimp-2.10.app/contents/macos/gimp -idf --batch-interpreter python-fu-eval -b "import sys;sys.path=['.']+sys.path;import OAFE_PARAM;OAFE_PARAM.open_add_flatten_export('/Users/TimB/Desktop/xcftemplate.xcf', '/Users/TimB/Desktop/jpg_to_add.jpg', 2060, 410, '/Users/TimB/Desktop/')" -b "pdb.gimp_quit(1)"
This does not work. My command line arguments are ignored, and I see a message "GIMP-Warning: The batch interpreter 'python-fu-eval' is not available. Batch mode disabled."
To troubleshoot I tried just launching the Gimp UI from a shell script and even that doesn't work properly. It loads strangely with broken icons (see image below). Any ideas what I can do to fix this? Am I doing something wrong in how I'm trying to launch Gimp?
Gimp UI screenshot
Here's my script to launch Gimp that fails:
#!/bin/bash
arg1="/Users/TimB/Desktop/xcf_template.xcf" #XCF file to open
arg2="/Users/TimB/Desktop/jpg_to_add.jpg" # JPG to insert
arg3=2060 # x_offset
arg4=410 # y_offset
arg5="/Users/TimB/desktop/" # save location
echo
echo "arg1 is" $arg1
echo "arg2 is" $arg2
echo "arg3 is" $arg3
echo "arg4 is" $arg4
echo "arg5 is" $arg5
/applications/gimp-2.10.app/contents/macos/gimp -idf --batch-interpreter python-fu-eval -b "import sys;sys.path=['.']+sys.path;import OAFE_PARAM;OAFE_PARAM.open_add_flatten_export('/Users/TimB/Desktop/xcftemplate.xcf', '/Users/TimB/Desktop/jpg_to_add.jpg', 2060, 410, '/Users/TimB/Desktop/')" -b "pdb.gimp_quit(1)"
UPDATE (3-27-2021):
I followed Mark's suggestion by removing my alias, ensuring that /usr/local/bin is on my PATH, and I created a symlink with sudo ln -s /applications/gimp-2.10.app/contents/macos/gimp /usr/local/bin/gimp. That still lets me launch Gimp by typing "Gimp" in terminal, but it still fails from within a shell script. I get this message.
The shell script is very simple:
#!/bin/bash
gimp
Here's the error I get:
../../../../gtk/source/babl-0.1.78/babl/babl-internal.h:214 void babl_log(const char *, ...)()
WARNING: the babl installation seems broken, no extensions found in queried
BABL_PATH (/Users/distiller/gtk/inst/lib/babl-0.1) this means no SIMD/instructions/special case fast paths and
only slow reference conversions are available, applications might still
run but software relying on babl for conversions will be slow
2021-03-27 11:27:22.180 gimp[85955:1451980] *** WARNING: Method userSpaceScaleFactor in class NSView is deprecated on 10.7 and later. It should not be used in new applications. Use convertRectToBacking: instead.
Cannot spawn a message bus without a machine-id: Unable to load /var/lib/dbus/machine-id or /etc/machine-id: Failed to open file “/var/lib/dbus/machine-id”: No such file or directory
../../../../gtk/source/babl-0.1.78/babl/babl-internal.h:222 void babl_fatal(const char *, ...)()
const Babl *babl_format(const char *)("CIE Lab double"): not found
sh: gdb: command not found
I got the same error today on macOS 12.4, Monterey. Gimp and babl installed through brew. Even when I run it as:
BABL_PATH=/usr/local/lib/babl-0.1 gimp
it still fails.
../babl/babl-internal.h:222 void babl_fatal(const char *, ...)() const Babl *babl_model(const char *)("RGBA"): you must call babl_init first
Unable to find Mach task port for process-id 17902: (os/kern) failure (0x5).
(please check gdb is codesigned - see taskgated(8))
/tmp/babl.gdb:1: Error in sourced command file:
No stack.
The gdb error is not related. I just didn't sign it yet. If I start gimp by clicking on the icon then it works though. But not from the cmdline.

Run Python script at startup in Ubuntu

I have a short Python script that needs to run at startup - Ubuntu 13.10. I have tried everything I can think of but can't get it to run. The script:
#!/usr/bin/python
import time
with open("/home/username/Desktop/startup.txt", 'a') as f:
f.write(str(time.time()) + " It worked!")
(The actual script is a bit different, as I'm just using this for testing purposes, but you get the idea.)
I've tried all of the following, with no luck:
Put the command python startuptest.py in crontab, as #reboot
python /home/username/Documents/startuptest.py, both as the regular user and as sudo
Put the command python /home/username/Documents/startuptest.py in /etc/rc.local
Opened Ubuntu's Startup Applications and put the command there
Done all of the preceding, putting the command into a shell script
and calling that shell script instead
Nothing works. I get the feeling I'm missing something simple. Any ideas? (The script runs fine if I just run the command from a terminal.)
Instructions
Copy the python file to /bin:
sudo cp -i /path/to/your_script.py /bin
Add A New Cron Job:
sudo crontab -e
Scroll to the bottom and add the following line (after all the #'s):
#reboot python /bin/your_script.py &
The “&” at the end of the line means the command is run in the background and it won’t stop the system booting up.
Test it:
sudo reboot
Practical example:
Add this file to your Desktop: test_code.py (run it to check that it works for you)
from os.path import expanduser
import datetime
file = open(expanduser("~") + '/Desktop/HERE.txt', 'w')
file.write("It worked!\n" + str(datetime.datetime.now()))
file.close()
Run the following commands:
sudo cp -i ~/Desktop/test_code.py /bin
sudo crontab -e
Add the following line and save it:
#reboot python /bin/test_code.py &
Now reboot your computer and you should find a new file on your Desktop: HERE.txt
Put this in /etc/init (Use /etc/systemd in Ubuntu 15.x)
mystartupscript.conf
start on runlevel [2345]
stop on runlevel [!2345]
exec /path/to/script.py
By placing this conf file there you hook into ubuntu's upstart service that runs services on startup.
manual starting/stopping is done with
sudo service mystartupscript start
and
sudo service mystartupscript stop
If you are on Ubuntu you don't need to write any other code except your Python file's code , Here are the Steps :-
Open Dash (The First Icon In Sidebar).
Then type Startup Applications and open that app.
Here Click the Add Button on the right.
There fill in the details and in the command area browse for your Python File and click Ok.
Test it by Restarting System . Done . Enjoy !!
Create file ~/.config/autostart/MyScript.desktop
with
[Desktop Entry]
Encoding=UTF-8
Name=MyScript
Comment=MyScript
Icon=gnome-info
Exec=python /home/your_path/script.py
Terminal=false
Type=Application
Categories=
X-GNOME-Autostart-enabled=true
X-GNOME-Autostart-Delay=0
It helps me!
In similar situations, I've done well by putting something like the following into /etc/rc.local:
cd /path/to/my/script
./my_script.py &
cd -
echo `date +%Y-%b-%d_%H:%M:%S` > /tmp/ran_rc_local # check that rc.local ran
This has worked on multiple versions of Fedora and on Ubuntu 14.04 LTS, for both python and perl scripts.
nano /etc/rc.local
and edit in
python ~/path-to-script.py
worked for me

Categories

Resources