Passing variables from Python GUI to PowerShell - python

So I am creating an application that can connect printers with a Python GUI that runs PowerShell scripts in the background. I was wondering if there was a way I could pass a variable inputted from a Python widget into a PowerShell script that is being invoked by Python. This variable would be the name of the printer that I could specify in Python so that I do not have to create separate scripts for each printer.
My code in Python that calls upon the PS script:
def connect():
if self.printerOpts.get() == 'Chosen Printer':
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe",'-ExecutionPolicy','Unrestricted', '.\'./ScriptName\';'])
PS script that connects printer to computer:
Add-Printer -ConnectionName \\server\printer -AsJob
Basically, I am wondering if I can pass a variable from Python into the "printer" part of my PS script so that I do not have to create a different script for each printer that I would like to add.

A better way to do this would be completely in PowerShell or complete in Python.
What you're after is doable. You can pass it in the same way that you have passed -ExecutionPolicy Unrestricted, by ensuring that the PowerShell script is expecting the variable.
My Python is non-existant so please bear with if that part doesn't work.
Python
myPrinter # string variable in Python with printer name
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe",'-ExecutionPolicy','Unrestricted', '.\'./ScriptName\';','-printer',myPrinter])
PowerShell
param(
$printer
)
Add-Printer -ConnectionName \\server\$printer -AsJob

The way that worked for me was first to specify that I was passing a variable as a string in my PS script:
param([string]$path)
Add-Printer -ConnectionName \\server\$path
My PS script was not expecting this variable. In my Python script I had to first define the my variable which named path as a string and then input "path" into the end of my subprocess function.
path = "c"
subprocess.call(["C:\\WINDOWS\\system32\\WindowsPowerShell\\v1.0\\powershell.exe",'-ExecutionPolicy','Unrestricted', 'Script.ps1', path])

Related

Executing a profile load shell script from a python program [duplicate]

This question already has answers here:
how to "source" file into python script
(8 answers)
Closed 3 years ago.
I am struggling to execute a shell script from a Python program. The actual issue is the script is a load profile script and runs manually as :
. /path/to/file
The program can't be run as sh script as the calling programs are loading some configuration file and so must need to be run as . /path/to/file
Please do guide how can I integrate the same in my Python script? I am using subprocess.Popen command to run the script and as said the only way it works is to run as . /path/to/file and so not giving the right result.
Without knowledge of the precise reason the script needs to be sourced, this is slightly speculative.
The fundamental problem is this: How do I get a source command to take effect outside the shell script?
Let's say your sourced file does something like
export fnord="value"
This cannot (usefully) be run in a subshell (as a normally executed script would) because the environment variable and its value will be lost when the script terminates. The solution is to source (aka .) this snippet from an already running shell; then the value stays in that shell's environment until that shell terminates.
But Python is not a shell, and there is no general way for Python to execute arbitrary shell script code, short of reimplementing the shell in Python. You can reimplement a small subset of the shell's functionality with something like
with open('/path/to/file') as shell_source:
lines = shell_source.readlines()
for line in lines:
if line.strip().startswith('export '):
var, value = line[7:].strip().split('=', 1)
if value.startswith('"'):
value = value.strip('"')
elif value.startswith("'"):
value = value.strip("'")
os.environ[var] = value
with some very strict restrictions (let's not say naïve assumptions) on the allowable shell script syntax in the file. But what if the file contained something else than a series of variable assignments, or the assignment used something other than trivial quoted strings in the values? (Even the export might or might not be there. Its significance is to make the variable visible to subprocesses of the current shell; maybe that is not wanted or required? Also export variable=value is not portable; proper Bourne shell script syntax would use variable=value; export variable or one of the many variations.)
If you know what exactly your Python script needs from the shell script, maybe do something like
r = subprocess.run('. /path/to/file; printf "%s\n" "$somevariable"',
shell=True, capture_output=True, text=True)
os.environ['somevariable'] = r.stdout.split('\n')[-2]
to source the entire script in a subshell, then print to standard output the part you actually need, and capture that from your Python script (and assign it to an environment variable if that's what you eventually need to accomplish).

how to pass an argument from python code to bash script?

I have a python code in which at the beginning it takes a string variable let say "element_name" from user and build some sub-folders based on this string and also some output files created by this code move to those folders.
On the other hand, I have a bash script in which some codes should be running in the sub-folders made in python code.
Any help how to introduce those folders in bash? How to pass the "element_name" from python to bash?
In python code "a.py" I tried
first = subprocess.Popen(['/bin/echo', element_name], stdout=subprocess.PIPE)
second = subprocess.Popen(['bash', 'path/to/script', '--args'], stdin=first.stdout)
and then in bash
source a.py
echo $element_name
but it doesn't work.
It's not clear from your question what is in your scripts, but I guess
subprocess.run(['/bin/bash', 'path/to/script', '--args', element_name])
is doing what you intend to do, passing the value of element_name to script as an argument.
I found a way. What I did is to pass the argument in a bash file and import this bash file as a source to my main bash file. Now everything works well.

Access a script's variables and functions in interpreter after runtime

So let's say I have a script script1. Is there a way to interact with script1's variables and functions like an interpreter after or during its runtime?
I'm using IDLE and Python 2.7, but I'm wondering if I could do this in any interpreter not just IDLE's.
Say in my script, get = requests.get("example.com"). I'd like to hit F5 or whatever to run my script, and then instead of the console unloading all of the variables from memory, I'd like to be able to access the same get variable.
Is this possible?
That's a serious question. You might need to consult this page:
https://docs.python.org/2/using/cmdline.html#miscellaneous-options
Note the -i option, it makes interpreter enter interactive mode after executing given script.
you can do like this:
#file : foo.py
import requests
def req():
get = requests.get("example.com")
return get
and then run the script from a console
import foo
get = foo.req()

Assign action to variable in Automator for use in Shell Script

Ok, this thing is driving me crazy right now. So Action 1 Chooses a Folder (I want to save that folder's path as var_1) and Action 3 Selects a File (I want to save this file's path as var_2)
so in the end . . .
var_1 = '/Users/Prometheus/Desktop/'
var_2 = '/Users/Prometheus/Documents/a.txt'
So how do I use these variables and their values inside of Shell Script with python ? I can't use sys.argv because they are set to some weird variables
I usually put 'Ask for Finder Item' > Run Shell Script and then
import sys
variable = open(argv[1]).read()
but i can't use that in this case . my scripts are in python so i'd rather stay in python because i don't know any other language
The Automator variables are only used in the Automator workflow. The variable themselves are not directly accessible to either a shell script or a Python script. The Run Shell Script action allows you to pass the values of particular variables to a shell script in either of two ways: either piping them in through stdin or by passing them as execution arguments. For this sort of use case, the latter is easier. To start with, you need to pick Automator variable names in the Set Value of Variable and Get Value of Variable actions so the values selected can be retained between actions. Here's a very rudimentary workflow example where I've selected two folders:
You might use a Run AppleScript action like this to display the dialogs:
POSIX path of (choose folder default location (path to desktop))
result & linefeed & POSIX path of (choose file default location (path to desktop))
Then set "Pass input" to "to stdin" in the Run Shell Script action and use a script like this:
import sys
folder, file = sys.stdin.read().splitlines()

Running a .py script from bash, how can I pass a python variable back to the terminal once the .py is done running?

For example, in bash:
python my_py.py
# i get some variable my_var
Back to bash. I want to have $my_var!
You can write your variable and its value into an ini file from the python script.
In Values.ini file
my_var="value"
After executing python script, just invoke Values.ini using . operator
. Values.ini
Now your shell variable $my_var will be having the assigned value.
The advantage with this method is that you can assign any number of variables like this.
var1="value1"
var2="value2"
var3="value3"

Categories

Resources