Syntax error with Cloud 9? - python

I'm new to Cloud 9, and have made a script. I want the code to appear at the url https://python-william1835.c9.io and I receive the following message:
Important: use os.getenv(PORT, 8080) as the port and os.getenv(IP,0.0.0.0) as the host in your scripts!
when I run it.
So I put it in the script (along with import os of course). And when I run it again, it says:
File "/home/ubuntu/workspace/Python Projects/Python Enigma Program/main.py", line 14
os.getenv(IP, 0.0.0.0)
^
SyntaxError: invalid syntax
Can you tell me why it does this?

You get a SyntaxError because the literal 0.0.0.0 is syntactically invalid.
The message you're receiving is a bit misleading in this specific case. Additionally, the documentation page for os.getenv is unfortunately not as verbose as one would want.
But, if you look at the source code for getenv you'll see that all arguments must be of type str:
def getenv(key, default=None):
"""Get an environment variable, return None if it doesn't exist.
The optional second argument can specify an alternate default.
key, default and the result are str."""
return environ.get(key, default)
Changing your calls to:
os.getenv("PORT", "8080")
os.getenv("IP", "0.0.0.0")
Should work and you should have no problem using them.

Related

Python OPC UA call method without arguments gives error

I am trying to call a method with no input arguements which is as follows :
[1]
[1]: https://i.stack.imgur.com/tGFe9.png
So far I have tried this :
method=client.get_node("ns=5;s=Demo.StateMachines.Program01.Reset")
parent=client.get_node("ns=5;s=Demo.StateMachines.Program01")
output=parent.call_method(method)
but it given me this BadNotExecutable error:
"The executable attribute does not allow the execution of the method."(BadNotExecutable)
The server is telling you this method cannot be executed.
There doesn't appear to be anything wrong with your client, check the server configuration.

Python: Subprocess works different to terminal. What I have to change?

I have to Python scripts: Tester1.py and Tester2.py.
Within Tester1 I want to start from time to time Tester2.py. I also want to pass Tester2.py some arguments. At the moment my code looks like this:
Tester1:
subprocess.call(['python3 Tester2.py testString'])
Tester2:
def start():
message = sys.argv[1]
print(message)
start()
Now my problem: If I run with my terminal Tester2 like 'python3 Tester2.py testString'my console prints out testString. But if I run Tester1 and Tester1 tries to start Tester2, I get an IndexError: "list index out of range".
How do I need to change my code to get everything working?
EDIT:
niemmi told me that I have to change my code to:
subprocess.call(['python3', 'Tester2.py', 'testString'])
but now I get a No such file or directory Error although both scripts are in the same directory. Someone knows why?
You need to provide the arguments either as separate elements on a list or as a string:
subprocess.call(['python3', 'Tester2.py', 'testString'])
# or
subprocess.call('python3 Tester2.py testString')
Python documentation has following description:
args is required for all calls and should be a string, or a sequence of program arguments. Providing a sequence of arguments is generally preferred, as it allows the module to take care of any required escaping and quoting of arguments (e.g. to permit spaces in file names). If passing a single string, either shell must be True (see below) or else the string must simply name the program to be executed without specifying any arguments.

Python Fabric as a Library, execute and environments?

I've tried really hard to find this but no luck - I'm sure it's possible I just can't find and example or figure out the syntax for myself
I want to use fabric as a library
I want 2 sets of hosts
I want to reuse the same functions for these different sets of hosts (and so cannot us the #roles decorator on said functions)
So I think I need:
from fabric.api import execute, run, env
NODES = ['192.168.56.141','192.168.56.152']
env.roledefs = {'head':['localhost'], 'nodes':NODES}
env.user('r4space')
def testfunc ():
run('touch ./fred.txt')
execute(testfunc(),<somehow specific 'head' or 'nodes' as my hosts list and user >)
I've tried a whole range of syntax // hosts=NODES, -H NODES, user='r4space'....much more but I either get a syntax error or "host_string = raw_input("No hosts found. Please specify (single)""
If it makes a difference, ultimately my function defs would be in a separate file that I import into main where hosts etc are defined and execute is called.
Thanks for any help!
You have some errors in your code.
env.user('r4space') is wrong. Should be env.user = 'r4space'
When you use execute, the first parameter should be a callable. You have used the return value of the function testfunc.
I think if you fix the last line, it will work:
execute(testfunc, hosts = NODES)

Python if statement returning

I am having trouble with what is presumably a simple if statement. I am trying to pass through the type of VM file format to use. Even if I put VMDK or VHD, it still comes back with VMDK is an invalid type or VHD is an invalid type.
import sys
vmtype = sys.argv[3]
vmtype = str(vmtype).strip().upper()
## File format check
if vmtype is not ("VHD") or ("VMDK"):
print vmtype + " is an invalid type"
sys.exit()
I have tried the if statement with != and not putting the parameters in parentheses. I have searched the web for a while and have tried what I have found and am still running into the same issue.
FYI I am running Python 2.6.5
Try:
if vmtype not in ("VHD", "VMDK"):
Your current code parses as:
if (vmtype is not ("VHD")) or ("VMDK"):
Which is obviously wrong. Since ("VMDK") is a truthy value, the whole statement always be true. Therefore the if statement will always execute.
Note that even if you tried
if vmtype is not "VHD":
It would not work, because is tests identity, not value. You would use:
if vmtype != "VHD":

Make pylint tolerate Requests

When I test a module that uses Requests, pylint has a fit and claims that the various members of the Request object that I use do not exist. How can I fix this? I already run pylint with the --generated-members=objects option.
For example, this code runs fine:
import requests
response = requests.get('https://github.com/timeline.json')
print response.content
But pylint claims the field does not exist:
ID:E1103 Instance of 'Request' has no 'content' member (but some
types could not be inferred)
pylint warning and error messages can be configured.
First of all you can write a ${HOME}/.pylintrc to disable some messages for all pylint checks. You can generate a default version of this file using the --generate-rc-file option.
(See this question for a bit more information).
You can also do the configuration inside the sources analyzed. For example putting some comments at the beginning of the file. This will disable the messages for the whole file.
The comment are in the form: #pylint: disable=warning-code, and "warning-code" is one of the list found here.
You can also disable messages locally, putting the comment before or on the side of a statement/expression.
For example, this disables the "C0322" warning for the code inside the function:
def my_func():
#C0322 -> no space between operand and operator
#pylint: disable=C0322
return a+b
While putting the comment on the right disables it for the single line of code:
def my_func():
return a+b #pylint: disable=C0322
I think in your case you could either put a comment at the beginning of the functions that use the request, or, if you do not access it many times, you could put a comment on the right of the statements.

Categories

Resources