I have the following situation.
I have a cli made in python in another folder and I have a function that receives some parameters and needs to be passed to the cli through an exec.
Estrutura de pastas
-execs
-fil1e.py
main.py
I tried to do it that way and it didn't work:
My main file
import sys
n = sys.argv [0]
stream = open ("execs / file1.py", n)
read_file = stream.read ()
exec(read_file)
Related
replace "Variables config" with "Variables /path/CLOUD234/__init__.py" in robot framework .Cloud instance is defined at run time .In each run the value changes ,so I have created a python file initpath.py as follows with fun() keyword .It will return the required path .How can I call it in Variables section of robot framework ? Thank you in advance.
import socket
import re
import os
def fun():
name = socket.gethostname()
pattern = ".*CLOUD[0-9]*"
hname = re.findall(pattern,name)
cloud_instance = hname[0].replace("-","_")
init_file = "/path/{}/__init__.py".format(cloud_instance)
return init_file
Variables section do not execute any code.
I suggest you run the python under testcase/suite up and use Set Test Variable to set the variable.
Try following: Here, you are not required to use any variables/section to call py file.
Under *** Settings *** section add
Library initpath.py
I am trying to run a script that sequentially changes some parameters in a config file (MET_config_EEv40.cfg) and runs a script ('IS_MET_EEv40_RAW.py') that retrieves these new config parameters:
config_filename = os.getcwd() + '/MET_config_EEv40.cfg'
import sys
parser = configparser.ConfigParser()
parser.read('MET_config_EEv40.cfg')
parser.set('RAW', 'product', 'ERA')
parser.set('RAW', 'gee_product', 'ECMWF/ERA5_LAND/HOURLY')
parser.set('RAW', 'indicator', 'PRCP')
parser.set('RAW', 'resolution', '11110')
with open('MET_config_EEv40.cfg', 'w') as configfile:
parser.write(configfile)
## execute file
import sys
os.system(exec(open('IS_MET_EEv40_RAW.py').read()))
#exec(open('IS_MET_EEv40_RAW.py').read())
print('I am here')
After this execution, I get the output of my script as expected:
Period of Reference: 2005 - 2019
Area of Interest: /InfoSequia/GIS/ink/shp_basin_wgs84.shp
Raw data is up to date. No new dates available in raw data
Press any key to continue . . .
But it never prints the end line: I am here, so that means that after the execution of the script, the algorithm is terminated. That is not what I want it to do, as I would like to be able to change some other config parameters and run the script again.
That output is showed because of this line of the code:
if (delta.days<=1):
sys.exit('Raw data is up to date. No new dates available in raw data')
So could be that sys.exit is ending both processes? Any ideas to replace sys.exit() inside the code to avoid this?
Im executing this file from a .bat file that contains the following:
#echo OFF
docker exec container python MET/PRCPmain.py
pause
exec(source, globals=None, locals=None, /) does
Execute the given source in the context of globals and locals.
So
import sys
exec("sys.exit(0)")
print("after")
is same as writing
import sys
sys.exit(0)
print("after")
which obviously terminate and does not print after.
exec has optional argument globals which you can use to provide your alternative to sys for example
class MySys:
def exit(self, *args):
pass
exec("sys.exit(0)",{"sys":MySys()})
print("after")
which does output
after
as it does use exit from MySys instance. If your codes make use of other things from sys and want it to work normally you would need method mimicking sys function in MySys class
I am currently attempting to pass a variable from my C# winforms application to my Python executable through process.start(). The script uses shutil to duplicate and rename a separate python file, the file will be renamed with respect to a variable (var, c# variable)...
I want to pass the "current" text-box value of my winforms
application to my Python script and run into a name error on my
python script. In my script, after clicking a button ,through
openFileDialog, I select a excel sheet file in the FileDialog and the
full path to the file is pasted in a textbox, "Textboxpath." Here I
want to pass the textbox value (the Textboxpath value) of my winforms application to my Python script.
My issue is defining the C# variable current value or value to my Python script. My windows form application runs perfectly with the current script though when I attempt to run my Python script and pass the C# variable through ".Arguments", my Python file returns with "NameError: name 'Textboxpath' is not defined." I have attempted to rewrite the process.start() function including the variable in my python script there has been no success to defining the variable, any help would be very appreciated!
**C#:**
...
#script for defining openFileDialog variable and using OpenFileDialog goes here
Textboxpath.Text = openFileDialog.FileName; #prints file (excel workbook) directory path to text box
...
string var;
var = Textboxpath.Text;
ProcessStartInfo StartInfo
= new ProcessStartInfo(#"C:\directorytask\dist\modifyfest.exe");
StartInfo.FileName = "C:\\directorytask\\dist\\modifyfest.exe";
StartInfo.Arguments = var;
Process.Start(StartInfo);
**Python script: modifyfest.exe** #packaged with pyinstaller, --onefile
import os
import sys
import shutil
x = var
f = x - '.xlsx'
l = f - 'C:\directorytask'
k = '.py'
y = 'test_'
z = y + l +k
#duplicating/renaming python file
original = 'C:/directorytask/test_five.py' #original python file
target = 'C:/directorytask/' + z #original python file being duplicated with name z
shutil.copyfile(original, target)
**Error:**
Traceback <most recent call last>:
File "modifyfest.py", line 5, in <module>
NameError: name 'Textboxpath' is not defined
[34652] failed to execute script modifyfest
I added the parser! This is how the Python script looks now, runs perfect...
**answer:**
import os
import sys
import shutil
from pathlib import Path
def parse(p):
q = p
return q
x = parse(sys.argv[1]) #imports first argument sent by c#, I attempted sys.argv[0] instead and it returned the first line of my c# ProcessStartInfo list, file name...
p = Path(x).stem
k = '.py'
y = 'test_'
z = y + p +k
original = 'C:/directorytask/test_five.py' #retailer specific duplicated task
target = 'C:/directorytask/' + z #task being created
shutil.copyfile(original, target)
I need to create an AWS Lambda version of an existing Python 2.7 program written by someone else who has left the company.
Using one function I need to convert as an example:
#!/usr/bin/env python
from aws_common import get_profiles,get_regions
from aws_ips import get_all_public_ips
import sys
def main(cloud_type):
# csv header
output_header = "profile,region,public ip"
profiles = get_profiles(cloud_type)
regions = get_regions(cloud_type)
print output_header
for profile in profiles:
for region in regions:
# public_ips = get_public_ips(profile,region)
public_ips = get_all_public_ips(profile,region)
for aws_ip in public_ips:
print "%s,%s,%s" % (profile,region,aws_ip)
if __name__ == "__main__":
cloud_type = 'commercial'
if sys.argv[1]:
if sys.argv[1] == 'govcloud':
cloud_type = 'govcloud'
main(cloud_type)
I need to know how to create this as an AWS handler with event and context arguments from the code above.
If I could get some pointers on how to do this it would be appreciated.
You can simply start writing python function inside the handler of aws labda.
in handler simply start defining functions and variables and uplaod zip file inside lambda if there is any type of dependency.
you can change the python version in lambda as per if you are using python 2.7.
i would like to suggest server less framework and uplaoding your code to lambda. it's so easy to manage dependency code management from locally.
here you are using aws_common and importing you have to check it is inside aws sdk or not.
you can import aws-sdk and use it
var aws = require('aws-sdk');
exports.handler = function (event, context)
{
}
inside exports handler you can start making for loops in python or goes further
So, I am passing a environment variable from bash to python;
#!/usr/bin/env python2
import os
#connect("weblogic", "weblogic", url=xxx.xxx.xxx.xxx:xxxx)
os.environ['bash_variable']
via wlst.sh I can print exported bash_variable, but how do I execute stored variable? Basically, I am trying to remove the original connect statement and pass a variable that has said information. Thanks
Question though, why wouldn't you called the script with the variable as an argument and use sys.argv[] ?
By example something like this.
import os
import sys
import traceback
from java.io import *
from java.lang import *
wlDomain = sys.argv[1]
wlDomPath = sys.argv[2]
wlNMHost = sys.argv[3]
wlNMPort = sys.argv[4]
wlDPath="%s/%s" %(wlDomPath,wlDomain)
wlNMprop="/apps/bea/wls/scripts/.shadow/NM.prop"
try:
print "Connection to Node Manager"
print ""
loadProperties(wlNMprop)
nmConnect(username=NMuser,password=NMpass,host=wlNMHost,port=wlNMPort,domainName=wlDomain,domainDir=wlDPath,mType='ssl',verbose='true')
except:
print "Fatal Error : No Connection to Node Manager"
exit()
print "Connected to Node Manager"
The NM.prop file is a 600 file with the username/password for the NM.
EDIT :
So from what I understand you want to do something like this :
URLS = ['t3s://Host1:Port1','t3s://Host2:Port2','t3s://Host3:Port3']
for urls in URLS:
connect('somebody','password',urls)
{bunch of commands}
disconnect()
And the values of the list URLS would be define by the environment.
The way I see it you have 3 choices :
Have 1 script per environment, more or less identical save for the URLS list
Have 1 script but with a conditionnal branching on sys.argv[1] (the environment as a parameter) and create the list there.
Have 1 script which use a parameter file for each environment according to the environment. Each parameter file containing the list in question.
Something like that :
propENV = sys.argv[1]
propPath = "/path1/path2"
propFile = "%s/%s" %(propPath,propENV)
loadProperties(propFile)
I would probably use the properties file option myself as it is more flexible from an operational standpoint...at least IMHO.