I'm new to python and having some issues with blocking. I have a script that I'm calling with options. I'm able to see the arguments come in, however, I have been unable to get the program to work correctly. In the code sample below, I'm trying to grab the arguments and then run the piece of code after the "#if ip address is not defined qpid-route will not work" comment. If I change the indentation after the comment, I get expected indentation or unexpected indentation errors.
The problem is that the way the code currently is it will run the elif opt in ("-i", "--ipaddress"): code and then will continue and run the code through to the bottom and then come back and run the -s loop code and then rerun the code to the bottom.
To fix this, I tried a break or continue command and all I get is indentation errors on this no matter which level I align it with. Can someone help me format this correctly such that I can pull the ipaddress and scac values that I'm grabbing from the arguments and then run the code after the "#if ip address is not defined qpid-route will not work" comment as a separate block.
import re
import os
import sys
import getopt
import pdb
ipaddress = ""
scac = ''
def main(argv):
#print argv
ipaddress = ""
scac = ''
pdb.set_trace()
try:
opts, args = getopt.getopt(argv,"hi:s:",["ipaddress=","scac="])
if not opts: # if no option given
print 'usage test.py -i <ipaddress> -s <scac>'
sys.exit(2)
except getopt.GetoptError:
print 'test.py -i <ipaddress> -s <scac>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'FedConnectStatus.py -i <iobipaddress> -s <scac>'
sys.exit() # it should be on level of if
elif opt in ("-i", "--ipaddress"):
ipaddress = arg
#break
#continue
elif opt in ("-s", "--scac"):
scac = arg
#if ip address is not defined qpid-route will not work
if not ipaddress:
print 'ip address needed'
else:
print(os.getcwd())
#If no scac is given grab every federated connection and report
if not scac:
# open file to read
f = file('qpid.txt', 'r')
nameList = []
statusList = []
#skip first 4 lines
for i in range(3): f.next() # skip first four lines
# iterate over the lines in the file
for line in f:
# split the line into a list of column values
columns = line.split(None, 5)
# clean any whitespace off the items
columns = [col.strip() for col in columns]
# ensure the column has at least one value before printing
if columns:
#print "Name", columns[0] # print the first column
#print "Status", columns[4] # print the last column
nameList.append(columns[0])
statusList.append(columns[4])
#print name
#print status
#else:
print nameList
print statusList
#if __name__ == "__main__":
main(sys.argv[1:])
This statement if not scac: on line 40 and below has indentation different to that of the rest of the code.
You'll see line 38 also doesn't match the indenting of the above if.
Related
It could be I'm completely misunderstanding the getopt module
I am trying to parse [--magic-m] to my program, but it does not set the correct field.
Part of Encrypt Function
def encrypt(filename, text, magic):
if not magic is None:
hash = pbkdf2_sha256.encrypt(magic, rounds=10000, salt_size=16)
print pbkdf2_sha256.verify(magic, hash)
try:
d = load_image( filename )
except Exception,e:
print str(e)
Part of Load function
def load_image( filename ) :
img = Image.open( os.path.join(__location__, filename) )
img.load()
data = np.asarray( img, dtype="int32" )
return data
Main
if __name__ == "__main__":
if not len(sys.argv[1:]):
usage()
try:
opts,args = getopt.getopt(sys.argv[1:],"hedm:",["help", "encrypt", "decrypt", "magic="])
except getopt.GetoptError as err:
print str(err)
usage()
magic = None
for o,a in opts:
if o in ("-h","--help"):
usage()
elif o in ("-e","--encrypt"):
to_encrypt = True
elif o in ("-d","--decrypt"):
to_encrypt = False
elif o in ("-m", "--magic"):
magic = a
else:
assert False,"Unhandled Option"
print magic
if not to_encrypt:
filename = sys.argv[2]
decrypt(filename, magic)
else:
filename = sys.argv[2]
text = sys.argv[3]
encrypt(filename, text, magic)
I tried calling the program above like this:
[1] python stego.py -e test.jpeg lol -m h
or like this:
[2] python stego.py -e -m h test.jpeg lol
Output becomes:
[1] None
[2] lol
[2] True
[2] [Errno 2] No such file or directory: 'C:\\Users\\Educontract\\Steganography\\-m'
Whitout the option -m everything works fine
The colon should come after m to indicate that it requires an argument. You should also include an equals sign after the long option magic to indicate that it requires an argument.
getopt.getopt(sys.argv[1:],"hedm:",["help", "encrypt", "decrypt", "magic="])
You should put all your options before the arguments, as in your second example.
python stego.py -e -m h test.jpeg lol
If you print sys.argv, I think you'll find that sys.argv[2] and sys.argv[3] are not what you expect. I would fetch the arguments from args, rather than sys.argv.
filename = args[0]
text = args[1]
Note that you may find it easier to use the argparse library instead of getopt. It isn't as strict about requiring options before arguments.
When I run then i get error.why print man gave error and also os.getwd() also give error.But when i comment that then there is no error.code works according to expectation
from __future__ import print_function;
import os
man=[]
other = []
print os.getcwd()
try:
data = open("sketch.txt")
for each_line in data:
try:
(role,line_spoken) = each_line.split(':',1)
line_spoken = line_spoken.strip()
if role=='Man':
man.append(line_spoken)
elif role =='Other Man':
other.append(line_spoken)
except ValueError:
pass
data.close()
except IOError:
print ("The Data File is Missing")
print man
print other
try:
man_file = open('man_data.txt','w')
other_file = open('other_data.txt','w')
print (man,file = man_file)
print (other,file = other_file)
other_file.close()
man_file.close()
except IOError:
pass
You should call print as function, because you import print_function:
from __future__ import print_function
print("Hello World")
As far as I see the following.
1) In the first line there is a ';' that could be removed.
2) the second line 'import...' and the rest to the bottom have tabs that should be removed. These lines should be in the same col that line 1 ('from ...')
3) when you use 'print' (as other people are saying) you should use '(' & ')'.
4) for coherence you should get used to follow the same approach in all your code (good practiceS), if there are no spaces between function names and parameters (i.e. line 7: data = open("sketch...) then go on with them. The same for strings, the code compile, but it is better if you use ' or " not mix them along the code.
looking forward to help!
How can I compare the values of input parmeters with a file in such a way that the sequence of the lines in file are "respected". For example:
file sequence.txt has following enteries
aaa
bbb
ccc
ddd
and the input is coming like this (with comas):
./run.py -c migrate -s ddd,bbb
then output is like this:
bbb
ddd
Here is the script I have worked so far
#!/usr/bin/python
import sys
import getopt
import time
import os
def main(argv):
cmd = ''
schemas = ''
script_dir = os.path.dirname(__file__)
seq_file = "system/sequence.txt"
abs_file_path = os.path.join(script_dir, seq_file)
try:
opts, args = getopt.getopt(argv,"h:c:s",["cmd=","schemas="])
except getopt.GetoptError:
print './run.py -c=<command> -s=<schemas> '
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print './run.py -c=<command> -s=<schemas>'
sys.exit()
elif opt in ("-c", "--cmd"):
cmd = arg
elif opt in ("-s", "--schemas"):
schemas = arg
if cmd == "migrate" :
with open(abs_file_path) as z:
for line in z:
print line.rstrip('\n')
if __name__ == "__main__":
main(sys.argv[1:])
I know that I have to do comparisons at position print line.rstrip('\n') but I can't figure out how to do it. Any suggestions?
Also, how can I make -s switch mandatory if -c has "migrate" value?
Thanks in advance.
You need to check whether the current line of the sequence is specified with the -s flag. So you need to modify the schemas value, so that it is a list that contains all schemas and then you can check if the current line is equal to one of the schemas. As for your second question, I'm not familiar with getopt, but you could simply check whether schemas is not empty when -c is migrate and do the approriate error handling.
[...]
schemas = []
[...]
elif opt in ("-s", "--schemas"):
schemas = arg.split(',')
[...]
if cmd == 'migrate':
if not schemas: # list is empty
# do error handling
for line in z:
if line in schemas:
print line
so i want to run this python program but i am unsure how to run it, when i insert in the arguments it get a token error.
First i "import cw2" which is the file name in the terminal after typing python and then i type in the argument to run a individual task but i get and error. Heres the code, can you tell me how to run the individual parts.
Heres what i typed as the argument cw2 -u user_745409913574d4c6 -d doc_140228202800-6ef39a241f35301a9a42cd0ed21e5fb0 -t task_2, But that doesnt work. Heres the code below showing what the argument is.
def main(argv):
user_uuid = ''
doc_uuid = ''
task_id = 0
try:
opts, args = getopt.getopt(argv, "hu:d:t:", ["user_uuid=", "doc_uuid=", "task_id="])
except getopt.GetoptError:
print 'cw2 -u <user_uuid> -d <doc_uuid> -t <task_id>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'cw2.py -u <user_uuid> -d <doc_uuid> -t <task_id>'
sys.exit()
elif opt in ("-u", "--user_uuid"):
user_uuid = arg
elif opt in ("-d", "--doc_uuid"):
doc_uuid = arg
elif opt in ("-t", "--task_id"):
task_id = arg
if(int(task_id) == 1):
with open("../requirements.txt", 'r') as fin:
print("Requirments.txt file content")
print fin.read()
if(int(task_id) == 2):
if(doc_uuid == ''):
print(" No doc_uuid supplied")
else:
task_2(doc_uuid)
print("Histograms for per country beed saved in : static/results/countries_to_book_UUID.png")
print("Histograms for per continent beed saved in : static/results/continent_to_book_UUI.png")
elif(int(task_id) == 3):
task_3()
print("Histograms of browser usage has been seaved in 'static/results/simple_browser_usage.png' ")
print("Histograms of generalised browser usage has been seaved in 'static/results/general_browser_usage.png")
elif(int(task_id) == 4):
print("Data of 10 most active readers")
task_4(10)
elif(int(task_id) == 5):
if((user_uuid == '') | (doc_uuid == '')):
print("Provide user_uuid or/and doc_uuid")
# 938601f24509a9f1 , 110727005030-000000009cca70787e5fba1fda005c85
else:
task_5(user_uuid, doc_uuid)
if __name__ == "__main__":
main(sys.argv[1:])
Don't run it from the Python shell, this is set up to run as a normal program from your terminal.
cd <wherever this script is>
chmod a+x ./cw.py
./cw.py -u user_745409913574d4c6 -d doc_140228202800-6ef39a241f35301a9a42cd0ed21e5fb0 -t task_2
Also, the indentation is all wrong on the script in your question, but I assume that that's a copy-and-paste error.
I have a python script that calls a system program and reads the output from a file out.txt, acts on that output, and loops. However, it doesn't work, and a close investigation showed that the python script just opens out.txt once and then keeps on reading from that old copy. How can I make the python script reread the file on each iteration? I saw a similar question here on SO but it was about a python script running alongside a program, not calling it, and the solution doesn't work. I tried closing the file before looping back but it didn't do anything.
EDIT:
I already tried closing and opening, it didn't work. Here's the code:
import subprocess, os, sys
filename = sys.argv[1]
file = open(filename,'r')
foo = open('foo','w')
foo.write(file.read().rstrip())
foo = open('foo','a')
crap = open(os.devnull,'wb')
numSolutions = 0
while True:
subprocess.call(["minisat", "foo", "out"], stdout=crap,stderr=crap)
out = open('out','r')
if out.readline().rstrip() == "SAT":
numSolutions += 1
clause = out.readline().rstrip()
clause = clause.split(" ")
print clause
clause = map(int,clause)
clause = map(lambda x: -x,clause)
output = ' '.join(map(lambda x: str(x),clause))
print output
foo.write('\n'+output)
out.close()
else:
break
print "There are ", numSolutions, " solutions."
You need to flush foo so that the external program can see its latest changes. When you write to a file, the data is buffered in the local process and sent to the system in larger blocks. This is done because updating the system file is relatively expensive. In your case, you need to force a flush of the data so that minisat can see it.
foo.write('\n'+output)
foo.flush()
I rewrote it to hopefully be a bit easier to understand:
import os
from shutil import copyfile
import subprocess
import sys
TEMP_CNF = "tmp.in"
TEMP_SOL = "tmp.out"
NULL = open(os.devnull, "wb")
def all_solutions(cnf_fname):
"""
Given a file containing a set of constraints,
generate all possible solutions.
"""
# make a copy of original input file
copyfile(cnf_fname, TEMP_CNF)
while True:
# run minisat to solve the constraint problem
subprocess.call(["minisat", TEMP_CNF, TEMP_SOL], stdout=NULL,stderr=NULL)
# look at the result
with open(TEMP_SOL) as result:
line = next(result)
if line.startswith("SAT"):
# Success - return solution
line = next(result)
solution = [int(i) for i in line.split()]
yield solution
else:
# Failure - no more solutions possible
break
# disqualify found solution
with open(TEMP_CNF, "a") as constraints:
new_constraint = " ".join(str(-i) for i in sol)
constraints.write("\n")
constraints.write(new_constraint)
def main(cnf_fname):
"""
Given a file containing a set of constraints,
count the possible solutions.
"""
count = sum(1 for i in all_solutions(cnf_fname))
print("There are {} solutions.".format(count))
if __name__=="__main__":
if len(sys.argv) == 2:
main(sys.argv[1])
else:
print("Usage: {} cnf.in".format(sys.argv[0]))
You take your file_var and end the loop with file_var.close().
for ... :
ga_file = open(out.txt, 'r')
... do stuff
ga_file.close()
Demo of an implementation below (as simple as possible, this is all of the Jython code needed)...
__author__ = ''
import time
var = 'false'
while var == 'false':
out = open('out.txt', 'r')
content = out.read()
time.sleep(3)
print content
out.close()
generates this output:
2015-01-09, 'stuff added'
2015-01-09, 'stuff added' # <-- this is when i just saved my update
2015-01-10, 'stuff added again :)' # <-- my new output from file reads
I strongly recommend reading the error messages. They hold quite a lot of information.
I think the full file name should be written for debug purposes.