is there any equivalent of
::set-output name=dir::sth
in python?
I've found module sh and I'm able to set it like this:
from sh import echo
echo(f"::set-output name=dir::sth")
but I'm wondering if there is any build in solution in python.
The python subprocess module is part of the standard library. I had success with it in GitHub actions by calling its Popen function:
steps:
- name: Create matrix object
id: create-matrix
shell: python
run: |
from os import getenv
from subprocess import Popen
import json
matrix_obj = {"prod-environment":[], "nice-app":[], "app-platform": []}
if getenv("ENV_PRODUCTION").lower() == "true":
matrix_obj["prod-environment"].append("production")
...
if getenv("APP_GA").lower() == "true":
matrix_obj["nice-app"].append("ga")
matrix_str = f'::set-output name=matrix::{json.dumps(matrix_obj)}'
print(f"Final matrix string: {matrix_str}")
Popen(['echo', matrix_str], bufsize=1)
env:
ENV_PRODUCTION: ${{inputs.env-production}}
APP_GA: ${{inputs.app-ga}}
...
Related
im using an email lookup module, called holehe (more can be found on it here - https://github.com/megadose/holehe) and i want to make it so when you enter an email it will automatically with in your python console output what came out from the new CMD window, makes it easier for my and colleges to use. How can i go about this? My code it bellow
import holehe
import os
from os import system
import subprocess
email = input("Email:")
p = subprocess.Popen(["start", "cmd", "/k", "holehe", email], shell = True)
p.wait()
input()
Thank you for answers
I have actualy python script running on background, you can see how it's displayed when i use command "ps -aux" :
root 405 0.0 2.6 34052 25328 ? S 09:52 0:04 python3 -u /opt/flask_server/downlink_server/downlink_manager.py
i want to check if this script are running from another python script, so i try to us psutil module, but it just detect that python3 are running but not my script precisely !
there is my python script :
import os
import psutil
import time
import logging
import sys
for process in psutil.process_iter():
if process.cmdline() == ['python3', '/opt/flask_server/downlink_server/downlink_manager.py']:
print('Process found: exiting.')
It's look like simple, but trust me, i already try other function proposed on another topic, like this :
def find_procs_by_name(name):
"Return a list of processes matching 'name'."
ls = []
for p in psutil.process_iter(attrs=["name", "exe", "cmdline"]):
if name == p.info['name'] or \
p.info['exe'] and os.path.basename(p.info['exe']) == name or \
p.info['cmdline'] and p.info['cmdline'][0] == name:
ls.append(p)
return ls
ls = find_procs_by_name("downlink_manager.py")
But this function didn't fin my script, it's work, when i search python3 but not the name of the script.
Of course i try to put all the path of the script but nothing, can you please hepl me ?
I resolve the issue with this modification :
import psutil
proc_iter = psutil.process_iter(attrs=["pid", "name", "cmdline"])
process = any("/opt/flask_server/downlink_server/downlink_manager.py" in p.info["cmdline"] for p in proc_iter)
print(process)
i am executing a r script from python and i want the output to be available in the python variable. how can i do that?
python script:
import subprocess
def runR(id, lat, long):
value = subprocess.popen("C:/R/R-3.2.0/bin/Rscript E:/Personal/python/script.R --args "+id+" "+lat+" "+long , shell=True)
print value
R script :
a = "Hello";
I want Hello to be availabe on the python variable value.
You could use rpy2:
import rpy2.robjects as robjects
robjects.r('''
a = "Hello";
''')
a = robjects.r['a']
As an alternative, you could rewrite your R script so that it would dump its result to stdout in some well-known format such as json, then run it using subprocess module, and parse the result:
#!/usr/bin/env python
import json
import subprocess
id, lat, long = 1, 40, 74
out = subprocess.check_output(r"C:\R\R-3.2.0\bin\Rscript.exe "
r"E:\path\to\script.R --args "
"{id} {lat} {long}".format(**vars()))
data = json.loads(out.decode('utf-8'))
Note: no need to use shell=True on Windows if you use the full path to the executable here.
You can modify the following example by your need.
a.py:
print 'hello'
b.py:
import subprocess
result = subprocess.check_output(["python", "a.py"])
print result.strip() + 'world'
Output of b.py:
helloworld
I want to create host_install.py from bash variables.
So I have tried following :
#!/bin/bash
CM_HOST="10.0.5.99"
CM_USER="admin"
CM_PASSWORD="admin"
CM_CLUSTER_NAME="cluster"
INSTANCE_TYPE=`wget -q -O- http://169.254.169.254/latest/meta-data/instance-type`
cat > /tmp/host_install.py <<EOF
import socket
import commands
from time import sleep
cluster_name = "$CM_CLUSTER_NAME"
role_template = "$INSTANCE_TYPE"
print cluster_name
print role_template
EOF
chmod a+x /tmp/host_install.py
/tmp/host_install.py
This is printing
$CM_CLUSTER_NAME
$INSTANCE_TYPE
instead of
cluster
c3.2xlarge
What wrong I am doing here ?
Environment variables are accessed through os.environ
import os
cluster_name = os.environ['CM_CLUSTER_NAME']
role_template = os.environ['INSTANCE_TYPE']
Python default installation on Windows is C:\Python. If you want to find out while running python you can do:
import sys
print sys.prefix
I'd like to do something like:
do lots of stuff to prepare a good environement
become_interactive
#wait for Ctrl-D
automatically clean up
Is it possible with python?If not, do you see another way of doing the same thing?
Use the -i flag when you start Python and set an atexit handler to run when cleaning up.
File script.py:
import atexit
def cleanup():
print "Goodbye"
atexit.register(cleanup)
print "Hello"
and then you just start Python with the -i flag:
C:\temp>\python26\python -i script.py
Hello
>>> print "interactive"
interactive
>>> ^Z
Goodbye
The code module will allow you to start a Python REPL.
With IPython v1.0, you can simply use
from IPython import embed
embed()
with more options shown in the docs.
To elaborate on IVA's answer: embedding-a-shell, incoporating code and Ipython.
def prompt(vars=None, message="welcome to the shell" ):
#prompt_message = "Welcome! Useful: G is the graph, DB, C"
prompt_message = message
try:
from IPython.Shell import IPShellEmbed
ipshell = IPShellEmbed(argv=[''],banner=prompt_message,exit_msg="Goodbye")
return ipshell
except ImportError:
if vars is None: vars=globals()
import code
import rlcompleter
import readline
readline.parse_and_bind("tab: complete")
# calling this with globals ensures we can see the environment
print prompt_message
shell = code.InteractiveConsole(vars)
return shell.interact
p = prompt()
p()
Not exactly the thing you want but python -i will start interactive prompt after executing the script.
-i : inspect interactively after running script, (also PYTHONINSPECT=x) and force prompts, even if stdin does not appear to be a terminal
$ python -i your-script.py
Python 2.5.4 (r254:67916, Jan 20 2010, 21:44:03)
...
>>>
You may call python itself:
import subprocess
print "Hola"
subprocess.call(["python"],shell=True)
print "Adios"