Want to verify if site domain contains "com". Assume I have shell varibale as
export FIRST_URL="http://www.11111.com"
export SECOND_URL="http://www.22222.org"
User calls Python script with parameter (partial shell varibale) as
python2.7 FIRST # OR
python2.7 SECOND
Python script is,
import sys, os, subprocess
PART_URL = sys.argv[1]
print( "PART_URL=",PART_URL)
COMPLETE_URL = PART_URL+'_URL' # Formed a full shell varibale
cmd_str='echo {} | grep \"com\".format(COMPLETE_URL)' # equivalent to echo $FIRST_URL | grep com
my_site=subprocess.check_output(cmd_str, shell=True) # Note we cant use subprocess.run() in Python Python 2.7
print("The validated Site is ", my_site)
The output should be "The validated Site is http://www.11111.com"
Refer How to access environment variable values?
$ export FIRST_VAR="http://www.11111.com"
$ python
>>> foo = 'FIRST'
>>> print os.environ[foo + '_VAR']
http://www.11111.com
>>>
Figured it out,
COMPLETE_URL = PART_URL+'_URL'
cmd_str='echo ${} | grep \'com\'.format(COMPLETE_URL)'
my_site=subprocess.check_output(cmd_str, shell=True)
Alteratively, we can use,
my_site=subprocess.call(shlex.split(cmd_str))
Related
I've been trying to make a script that can print the Ubuntu SSH key located in ~/.ssh/authorised_keys/
Basically I want the script to print out exactly what cat ~/.ssh/authorised_keys/ would output.
I have tried using subprocess.check_output but it always returns an error.
Thanks
What about this ?
import os
os.system('cat ~/.ssh/authorised_keys')
If you want to capture the output to a variable, use subprocess. If not, you can use os.system as user803422 has mentioned
import os, subprocess
path = '~/.ssh/authorized_keys'
cmd = 'cat ' + os.path.expanduser(path)
output = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
response = output.communicate()
print (response)
You can read the file directly in Python, there is not really a need to use subprocess:
import os
print(open(os.path.expanduser('~/.ssh/authorized_keys')).read())
I'm using the os package to set some environment variable, like this :
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
print ("--------------------------> : ", os.environ)
print '>>>> ',os.getenv('MY_ENV_APP')
if "MY_ENV_APP" not in os.environ:
print "not in !"
os.environ['MY_ENV_APP'] = "prod"
else:
print "ok, good boy !"
print '>>>> ',os.getenv('MY_ENV_APP')
print ("--------------------------> : ", os.environ)
The "MY_ENV_APP" is setting using os.environ, but NOT in Ubuntu system :
...
/usr/local/rvm/bin', 'MY_ENV_APP': 'prod', 'GEM_HOME': '/us
...
>>>> None
not in !
>>>> prod
...
/usr/local/rvm/bin', 'MY_ENV_APP': 'prod', 'GEM_HOME': '/us
...
System os :
[02:59 ]-[vagrant#host]-[/var/www/python]
$ printenv | grep -i my_env_app
[02:59 ]-[vagrant#host]-[/var/www/python]
$ printenv | grep MY_ENV_APP
[03:00 ]-[vagrant#host]-[/var/www/python]
$ echo $MY_ENV_APP
$[03:02 ]-[vagrant#host]-[/var/www/python]
So, the environment variable is setting "in python" but not in the system.
Can you help me please ?
Thanks,
Fabrice
Example:
MY_ENV_APP=abcdef python test.py
This will set the variable for this process only.
I am running a python script on my raspberry pi, at the end of which I want to call a second python script in the same directory. I call it using the os.system() command as shown in the code snippet below but get import errors. I understand this is because the system interprets the script name as a shell command and needs to be told to run it using python, using the shebang line at the beginning of my second script.
#!/usr/bin/env python
However doing so does not solve the errors
Here is the ending snippet from the first script:
# Time to Predict E
end3 = time.time()
prediction_time = end3-start3
print ("\nPrediction time: ", prediction_time, "seconds")
i = i+1
print (i)
script = '/home/pi/piNN/exampleScript.py'
os.system('"' + script + '"')
and here is the beginning of my second script:
'#!usr/bin/env python'
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
#from picamera import PiCamera
import argparse
import sys
import time
import numpy as np
import tensorflow as tf
import PIL.Image as Image
Any help is greatly appreciated :)
Since you have not posted the actual errors that you get when you run your code, this is my best guess. First, ensure that exampleScript.py is executable:
chmod +x /home/pi/piNN/exampleScript.py
Second, add a missing leading slash to the shebang in exampleScript.py, i.e. change
'#!usr/bin/env python'
to
'#!/usr/bin/env python'
The setup that you have here is not ideal.
Consider simply importing your other script (make sure they are in the same directory). Importing it will result in the execution of all executable python code inside the script that is not wrapped in if __name__ == "__main__":. While on the topic, should you need to safeguard some code from being executed, place it in there.
I have 2 python file a.py and b.py and I set execute permission for b.py with.
chmod a+x b.py
Below is my sample:
a.py
#!/usr/bin/python
print 'Script a'
import os
script = './b.py'
os.system('"' + script + '"')
b.py
#!/usr/bin/python
print 'Script b'
Execute "python a.py", the result is:
Script a
Script b
Simple script1.py that takes arguments and calls script2.py by passing them to os.system() :
#! /usr/bin/env python
import os
import sys
os.system("script2.py sys.argv[1] sys.argv[2]")
Running this :
./script1.py "arg1" "arg2"
Getting this single error :
sh: 1: script2.py: not found
Both scripts are present in the same directory.
Applied chmod 777 on both script1.py and script2.py and are executable.
Both scripts call the same interpreter installed at /usr/bin/env python.
When I try these :
os.system("./script2.py sys.argv[1] sys.argv[2]")
os.system("python script2.py sys.argv[1] sys.argv[2]")
The sys.argv[1] and sys.argv[2] are being considered as strings instead of dynamic variables
Have you tried with:
./script2.py "arg1" "arg2"
Inside the os.system?
UPDATE 2
Try with:
import urllib
call_with_args = "./script2.py '%s' '%s'" % (str(arg1), str(arg2))
os.system(call_with_args)
I would like to create env variables once to use elsewhere in my fabric file. For example:
from fabric.api import *
# environments
def dtconfig():
env.path = 'David'
# tasks
def hello():
require('path', provided_by=[dtconfig])
print (env.path)
print ('Hello $(path)')
print ('Hello ' + env.path)
The output from running 'fab dtconfig hello' is:
David
Hello $(path)
Hello David
Why doesn't the $(path) get replaced with 'David'? thx
Looks like bash variables were removed in later versions of fabric. just used plain old %s string substitutions instead.