[Tutor] python script

2015-02-20 Thread rohit poddaturi
Hi 

I am really new to python and have been given a assignment which is quite 
complex for my standard.The following is the assignment
 
The program runs through the word  document and when it sees a date ( the date 
might be in a variety of forms, but will always list the particular month) it 
goes to a new row  in the excel sheet and lists that date. Then it searches for 
a key word. If that key word appears before the next date in the document, then 
it lists it as a '1' in the excel sheet. If that key word does not appear 
before the next date listed then it writes down a '0’. 

I am attaching a sample document and excel output for reference. Kindly look 
into it 

Regards
Rohit Poddaturi











___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python script

2015-02-20 Thread Alan Gauld

On 20/02/15 03:56, rohit poddaturi wrote:

 The program runs through the word  document and when it sees a date
> ( the date might be in a variety of forms, but will always list the 
particular month)

>  it goes to a new row  in the excel sheet and lists that date.

OK, The first question that springs to mind is "How are you accessing 
the Word and Excel files?
They are not a native format that Python can easily read so you need 
some kind of library to work with them. Do you already have such a 
library or do you need to find one?


> Then it searches for a key word. If that key word appears before
> the next date in the document, then it lists it as a '1' in

the excel sheet.If that key word does not appear before the

> next date listed then it writes down a '0’.

The same applies for writing to Excel, you need a library to do that. Do 
you have one already?


Also which Python version are you using?
I'll assume you are running Windows since it is Word and Excel based?


I am attaching a sample document and excel output for reference. Kindly look 
into it


Your attachments didn't show up. Can you put them on a web site somewhere?

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] python script

2015-02-20 Thread Mark Lawrence

On 20/02/2015 03:56, rohit poddaturi wrote:

Hi

I am really new to python and have been given a assignment which is quite 
complex for my standard.The following is the assignment

The program runs through the word  document and when it sees a date ( the date 
might be in a variety of forms, but will always list the particular month) it 
goes to a new row  in the excel sheet and lists that date. Then it searches for 
a key word. If that key word appears before the next date in the document, then 
it lists it as a '1' in the excel sheet. If that key word does not appear 
before the next date listed then it writes down a '0’.

I am attaching a sample document and excel output for reference. Kindly look 
into it

Regards
Rohit Poddaturi



The attachments have not arrived so please put your code and a data 
sample inline for us to view.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] updating a dictionary

2015-02-20 Thread Peter Otten
Chris Stinemetz wrote:

> ​Here is a sample of the input data, it is tab delimited and I chopped it
> down for example purposes:
> ​
> 
>  KSL03502_7A_1 11.5921
> KSL03502_7B_1 46.4997
> KSL03502_7C_1 13.5839
> KSL03505_7A_1 12.8684
> KSL03505_7B_1 16.5311
> KSL03505_7C_1 18.9926
> KSL03509_7A_1 3.4104
> KSL03509_7B_1 40.6244
> KSL03509_7C_1 51.0597
> KSL03511_7A_1 7.128
> KSL03511_7B_1 53.4401
> KSL03511_7C_1 66.2584
> KSL03514_2A_1 25.6476
> KSL03514_2B_1 53.17
> KSL03514_2C_1 11.6469
> KSL03514_7A_1 39.2292
> KSL03514_7B_1 65.675
> KSL03514_7C_1 3.4937
> 
> 
> ​I would like to parse it buy using a dictionary structure. Where each row
> would be something like:
> 
> name 7,8,9,2
> KSL03514_C,3.4937,,,11.6469
> KSL03514_B,65.675,,,53.17
> 
> I am just showing an example of what KSL03514_7C_1, KSL03514_2C_1,
> KSL03514_7B_1, KSL03514_2B_1 would parse.
> 
> Hope this helps explain what I am trying to accomplish.

You need to merge multiple lines into one row dict and you'll end up with 
multiple such rowdicts. The easiest way to keep them around is to put them 
into an outer dict that maps keys like "KSL03514_B" to the corresponding 
rowdict. This will start with

{'2': '53.17', 'name': 'KSL03514_B'}

in line

> KSL03514_2B_1 53.17

and be updated to

{'7': '65.675', '2': '53.17', 'name': 'KSL03514_B'}

when line

> KSL03514_7B_1 65.675

is encountered. The "name" item is redundant because it's the same as the 
key in the outer dict


{'KSL03502_A': {'7': '11.5921', 'name': 'KSL03502_A'},
 'KSL03502_B': {'7': '46.4997', 'name': 'KSL03502_B'},
  ...
 'KSL03514_B': {'2': '53.17', '7': '65.675', 'name': 'KSL03514_B'},
 'KSL03514_C': {'2': '11.6469', '7': '3.4937', 'name': 'KSL03514_C'}}

but it simplifies generating the resulting file.

If you want to cheat, here's the code I came up with:

import csv
import operator
import sys
import logging

logger = logging.getLogger()


def read_data(infile):
"""Combine lines in infile with same  into one dict.

Returns a sorted list of such dicts.

Expected line format:
  __
where
   digits only
   non-digit followed by any non-"_"

Then
   = _
"""
# map  to rowdict
# rowdict maps  to  and "name" to 
rows_by_name = {}

for line in infile:
# key format:
# __
key, value = line.split()

basename, both, dummy = key.split("_")
suffix = both.lstrip("0123456789")
prefix = both[:len(both)-len(suffix)]
name = basename + "_" + suffix
rowdict = rows_by_name.setdefault(name, {"name": name})
if prefix in rowdict:
# we are going to overwrite a column value
# may raise an exception instead
logger.warn("duplicate column %s=%r for %s",
prefix, value, name)
rowdict[prefix] = value

return sorted(rows_by_name.values(), key=operator.itemgetter("name"))


def main():
logging.basicConfig()

with open("PRB_utilization.txt") as infile:
rows = read_data(infile)

writer = csv.DictWriter(
sys.stdout,  # may replace stdout with any writable file object
fieldnames=["name", "7", "8", "9", "2"]
)
writer.writeheader()
writer.writerows(rows)


if __name__ == "__main__":
main()


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] Issue in date difference in Python 2.7.8

2015-02-20 Thread Puruganti Ramesh
Hi Friends,

I have an issue in comparing dates in python 2.7.8
I have written code as below but i am getting error
Code is :
import datetime as dt
from datetime import datetime
from datetime import datetime, timedelta, date

dt_str='2014-5-11'
dt_strq='2014-9-11'

dt_datea = datetime.strptime(dt_str, '%Y-%m-%d').date()
dt_dateb = datetime.strptime(dt_strq, '%Y-%m-%d').date()
dt_diff = dt_dateb - dt_datea
print dt_diff.days

I am getting below excption
Traceback (most recent call last):
File "FunctionUpdate.py", line 204, in 
dt_dateb = datetime.strptime(dt_strq, '%Y-%m-%d').date()
File "/usr/local/lib/python2.7/_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains:

Kindly solve my issue

Regards,
Ramesh
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Issue in date difference in Python 2.7.8

2015-02-20 Thread Peter Otten
Puruganti Ramesh wrote:

> Hi Friends,
> 
> I have an issue in comparing dates in python 2.7.8
> I have written code as below but i am getting error
> Code is :
> import datetime as dt
> from datetime import datetime
> from datetime import datetime, timedelta, date
> 
> dt_str='2014-5-11'
> dt_strq='2014-9-11'
> 
> dt_datea = datetime.strptime(dt_str, '%Y-%m-%d').date()
> dt_dateb = datetime.strptime(dt_strq, '%Y-%m-%d').date()
> dt_diff = dt_dateb - dt_datea
> print dt_diff.days

No, the above does not trigger the ValueError.

> I am getting below excption
> Traceback (most recent call last):
> File "FunctionUpdate.py", line 204, in 
> dt_dateb = datetime.strptime(dt_strq, '%Y-%m-%d').date()
> File "/usr/local/lib/python2.7/_strptime.py", line 328, in _strptime
> data_string[found.end():])
> ValueError: unconverted data remains:
> 
> Kindly solve my issue

See my answer on comp.lang.python:




___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Issue in date difference in Python 2.7.8

2015-02-20 Thread Dave Angel

On 02/20/2015 04:28 AM, Puruganti Ramesh wrote:

Hi Friends,

I have an issue in comparing dates in python 2.7.8
I have written code as below but i am getting error
Code is :
import datetime as dt
from datetime import datetime
from datetime import datetime, timedelta, date

dt_str='2014-5-11'
dt_strq='2014-9-11'

dt_datea = datetime.strptime(dt_str, '%Y-%m-%d').date()
dt_dateb = datetime.strptime(dt_strq, '%Y-%m-%d').date()
dt_diff = dt_dateb - dt_datea
print dt_diff.days

I am getting below excption
Traceback (most recent call last):
File "FunctionUpdate.py", line 204, in 
dt_dateb = datetime.strptime(dt_strq, '%Y-%m-%d').date()
File "/usr/local/lib/python2.7/_strptime.py", line 328, in _strptime
data_string[found.end():])
ValueError: unconverted data remains:



I think it's great that you reduced a 200+ line program into a 9 line 
simple case.  that's always a good idea, and frequently it helps you 
solve your own problem, reducing it for public comment.


But the other requirement is that you actually test that the code you 
show produces the error you show.  It does not, probably because those 
strings in the literals are not exactly what you had in the original.



--
DaveA
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] updating a dictionary

2015-02-20 Thread Chris Stinemetz
I am getting closer. I think I have figured out the logic. I just have a
quick question. How do you access key:values in a nested dictionary?

MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]}

say I want to access the key:value 8:0

print dict['MOL02997_C']['8'] doesn't seem to work.

Thanks in advance.

On Thu, Feb 19, 2015 at 5:10 PM, Alan Gauld 
wrote:

> On 19/02/15 22:50, Emile van Sebille wrote:
>
>   if cell.endswith(suffix, 14, 16) is False:
>>>
>>
>> ... so they'll never end with numeric values.  Further, "".endswith()
>> accepts only one argument so you ought to get an error on this line.
>>
>
> Sorry Emile, The OP is correct.
>
> ##
> >>> help(''.endswith)
> endswith(...) method of builtins.str instance
> S.endswith(suffix[, start[, end]]) -> bool
>
> Return True if S ends with the specified suffix, False otherwise.
> With optional start, test S beginning at that position.
> With optional end, stop comparing S at that position.
> suffix can also be a tuple of strings to try.
> ###
>
> The tuple is the set of suffices and the numbers are the
> start/end points. Its not often seen like that but the
> OP is quite correct.
>
>
> The test against False is unusual it woyuld normally look like
>
>  if not cell.endswith(suffix, 14, 16):
>
> but that is just a style issue.
>
>
> --
> Alan G
> Author of the Learn to Program web site
> http://www.alan-g.me.uk/
> http://www.amazon.com/author/alan_gauld
> Follow my photo-blog on Flickr at:
> http://www.flickr.com/photos/alangauldphotos
>
>
> ___
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] updating a dictionary

2015-02-20 Thread Alan Gauld

On 20/02/15 17:56, Chris Stinemetz wrote:

I am getting closer. I think I have figured out the logic. I just have a
quick question. How do you access key:values in a nested dictionary?

MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]}

say I want to access the key:value 8:0

print dict['MOL02997_C']['8'] doesn't seem to work.


Look closer. The inner dictionary is inside a list [...].

try

print dict['MOL02997_C'][0]['8']


If that works then try to figure out where the extra list
is coming from and eliminate it.

--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos


___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] updating a dictionary

2015-02-20 Thread Mark Lawrence

On 20/02/2015 17:56, Chris Stinemetz wrote:

Please don't top post as it makes long threads difficult if not 
impossible to follow, thanks.



I am getting closer. I think I have figured out the logic. I just have a
quick question. How do you access key:values in a nested dictionary?

MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]}




say I want to access the key:value 8:0

print dict['MOL02997_C']['8'] doesn't seem to work.


"doesn't seem to work" doesn't tell us much, so normally you would post 
your code and the full traceback that you get.  However what you have 
seems to be a dictionary that you've called dict, hence overriding the 
Python built-in name.  This isn't illegal but it's certainly frowned 
upon.  For the key 'MOL02997_C' you have a list which holds one dict 
which contains a value '8' amongst others.  Hence:-


>>> mystruct = {'MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]}
>>> mystruct
{'MOL02997_C': [{'7': '0', '8': '0', '2': '0', '9': '0'}]}
>>> mystruct['MOL02997_C']
[{'7': '0', '8': '0', '2': '0', '9': '0'}]
>>> mystruct['MOL02997_C'][0]
{'7': '0', '8': '0', '2': '0', '9': '0'}
>>> mystruct['MOL02997_C'][0]['8']
'0'

Got that?

--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


[Tutor] subprocess outputing wrong info to command line

2015-02-20 Thread brads
My subprocess is in error but the same command at the command line works
fine.

 

 

# cat makekeys.py

#!/usr/bin/python3.4

import subprocess

import sys

import string

import os.path

import datetime

import shlex

from time import gmtime, strftime

from subprocess import Popen, PIPE, STDOUT

 

pretime = strftime("%Y%m%d%H", gmtime())

time = datetime.datetime.strptime(pretime,'%Y%m%d%H')

print (time)

plustime = datetime.timedelta(days=730)

timeadd = (time + plustime)

str(timeadd)

#ndate = datetime.strptime(timeadd, '%Y%m%d%H')

#timeadd = timeadd.replace(tzinfo=UTC())

print (timeadd)

 

dname = input("Enter the domain to configure keys for? ")

if os.path.exists(dname+".external.signed"):

os.remove(dname+".external.signed")

#os.remove(dname+".external")

os.remove(dname+".ksk.key")

os.remove(dname+".zsk.key")

os.remove(dname+".ksk.private")

os.remove(dname+".zsk.private")

fd = open( dname+".external", 'w')

fd.write("$TTL 86400\n")

fd.write("$ORIGIN "+dname+".\n")

fd.write("@  1D  IN SOA yoda.ex-mailer.com.  admin@"+dname+".(\n")

fd.write("  "+strftime("%Y%m%d%H", gmtime())+"\n")

#fd.write(" "+repr(timeadd)+"\n")

fd.write("  3h\n")

fd.write("  1h\n")

fd.write("  1w\n")

fd.write("  1h)\n")

fd.write("  IN NS   yoda.ex-mailer.com.\n")

fd.write("  IN NS   r2d2.ex-mailer.com.\n")

fd.write(dname+".   IN TXT  v=spf1 mx a:r2d2.ex-mailer.com
-all\n")

fd.write(dname+".   MX 0r2d2.ex-mailer.com.\n")

fd.write("mail."+dname+".   IN A107.191.60.48\n")

fd.write("$include /usr/local/etc/namedb/K"+dname+".zsk.key ; ZSK\n")

fd.write("$include /usr/local/etc/namedb/K"+dname+".ksk.key ; KSK\n")

fd.close()

 

 

result = subprocess.check_output(["dnssec-keygen", "-f", "KSK", "-r",
"/dev/urandom", "-a", "RSASHA256", "-b", "2048", "-n", "ZONE", dname])

result_utf8 = result.decode("utf-8").strip()

mylist = list(result_utf8)

print (mylist[0])

listlen= len(mylist)

array = list()

listlen -= 11

i = 0

while( i < listlen ):

#if mylist != '\n' ^ mylist != '':

array.insert(i, mylist[i])

i = i + 1

combined = "".join(array)

print ('combined')

print (combined)

fmove = subprocess.call(["mv", result_utf8+".key",combined +".ksk.key"])

fmove = subprocess.call(["mv", result_utf8+".private",combined
+".ksk.private"])

 

zresult =
subprocess.check_output(["dnssec-keygen","-r","/dev/urandom","-a","RSASHA256
","-b","2048","-n","ZONE", dname])

zresult_utf8 = zresult.decode("utf-8").strip()

myzlist = list(zresult_utf8)

print (myzlist[0])

zlistlen= len(myzlist)

zarray = list()

zlistlen -= 11

zi = 0

while( zi https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] updating a dictionary

2015-02-20 Thread Chris Stinemetz
On Fri, Feb 20, 2015 at 4:51 PM, Mark Lawrence 
wrote:

> On 20/02/2015 17:56, Chris Stinemetz wrote:
>
> Please don't top post as it makes long threads difficult if not impossible
> to follow, thanks.
>
>  I am getting closer. I think I have figured out the logic. I just have a
>> quick question. How do you access key:values in a nested dictionary?
>>
>> MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]}
>>
>
>
>> say I want to access the key:value 8:0
>>
>> print dict['MOL02997_C']['8'] doesn't seem to work.
>>
>
> "doesn't seem to work" doesn't tell us much, so normally you would post
> your code and the full traceback that you get.  However what you have seems
> to be a dictionary that you've called dict, hence overriding the Python
> built-in name.  This isn't illegal but it's certainly frowned upon.  For
> the key 'MOL02997_C' you have a list which holds one dict which contains a
> value '8' amongst others.  Hence:-
>
> >>> mystruct = {'MOL02997_C': [{'2': '0', '7': '0', '8': '0', '9': '0'}]}
> >>> mystruct
> {'MOL02997_C': [{'7': '0', '8': '0', '2': '0', '9': '0'}]}
> >>> mystruct['MOL02997_C']
> [{'7': '0', '8': '0', '2': '0', '9': '0'}]
> >>> mystruct['MOL02997_C'][0]
> {'7': '0', '8': '0', '2': '0', '9': '0'}
> >>> mystruct['MOL02997_C'][0]['8']
> '0'
>
> Got that?
>
>
>
​
Thank you Mark.

I understand what you are explaining to me but I am not sure why every
instance of the key 8:value changes when I assign a new value to it.

I am expecting only vals['KSL04523_A'][0]['8'] value to change to 55.55 but
as you can see bellow all rows in the dictionary are changes for key 8:

Thank you in advance

>>> vals['KSL04523_A']
[{'7': '0', '9': '0', '8': '0', '2': '0'}]
>>> vals['KSL04523_A'][0]
{'7': '0', '9': '0', '8': '0', '2': '0'}


>>> vals['KSL04523_A'][0]['8']
'0'


>>> vals['KSL04523_A'][0]['8'] = 55.55
>>> pprint.pprint(vals)
{'CELL_': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04514_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04514_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04515_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04515_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04515_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04516_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04516_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04516_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04517_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04517_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04517_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04519_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04519_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04519_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04520_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04520_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04520_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04521_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04521_B': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04521_C': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}],
 'KSL04523_A': [{'2': '0', '7': '0', '8': 55.55, '9': '0'}]}​
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] updating a dictionary

2015-02-20 Thread Danny Yoo
On Fri, Feb 20, 2015 at 3:47 PM, Chris Stinemetz
 wrote:
>
> I understand what you are explaining to me but I am not sure why every
> instance of the key 8:value changes when I assign a new value to it.


Ah.  Be wary of structure sharing when the values being shared are mutable.


A textbook example of this would be:

###
message = ['hello', 'world']
copy = message
copy.append('!')
print copy
print message
## What do we expect to see here?  What do we see?
###

The code above here is wrong to use the word "copy" here, because it's
not copying the structure at all.  copy refers to the *same* list
value.  Mutations to the value will be observable when we access that
list through either 'message' or 'copy', since fundamentally they're
both referring to the same list value.

To copy a list, we can use a whole slice:

#
message = ['hello', 'world']
copy = message[:]
copy.append('!')
print copy
print message
#


I don't know what your program looks like at this point, so I can't
pinpoint exactly where this is happening, but at the very least, this
should help you figure out what's going on.

Feel free to ask if you'd like more explanation.  If you'd like a
visualization, also see:

http://pythontutor.com/visualize.html#code=message+%3D+%5B'hello',+'world'%5D%0Acopy+%3D+message%0Acopy.append('!')&mode=display&origin=opt-frontend.js&cumulative=false&heapPrimitives=false&textReferences=false&py=2&rawInputLstJSON=%5B%5D&curInstr=0

and compare vs:

http://pythontutor.com/visualize.html#code=message+%3D+%5B'hello',+'world'%5D%0Acopy+%3D+message%5B%3A%5D%0Acopy.append('!')&mode=display&origin=opt-frontend.js&cumulative=false&heapPrimitives=false&textReferences=false&py=2&rawInputLstJSON=%5B%5D&curInstr=0


Good luck!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] subprocess outputing wrong info to command line

2015-02-20 Thread Steven D'Aprano
On Fri, Feb 20, 2015 at 06:58:17PM -0500, brads wrote:

> My subprocess is in error but the same command at the command line works
> fine.

Are you running the Python script as the same user and from the same 
location as the command line? If you are running the Python script as an 
unprivileged user from your home directory, and the command line as root 
from the directory holding the key, then it is not surprising that they 
will get different results.

Does the dnssec-signzone command use any environment variables? Perhaps 
they are not being inherited by the Python subprocess.

Also, a note about sending code to the list. For some reason, every line 
in your code is separated by blank lines:

> # cat makekeys.py
> 
> #!/usr/bin/python3.4
> 
> import subprocess
> 
> import sys

etc. That makes it very hard to read. Please fix that.

Secondly, you have a huge amount of extraneous code which is irrelevant 
to your problem with subprocess. You calculate dates, ask the user for 
input, delete files, and write new files, calculate arrays and more. 
None of that has anything to do with subprocess. Take it out. Reduce 
your problem to the smallest possible code which shows the problem. 9 
times out of 10, the process of cutting your code down to manageable 
size will actually help you to solve your own problem, and the other 1 
time out of 10 we have a smaller and less confusing piece of code to try 
to understand.

You also have dead, obsolete code commented out. Comments should not be 
used for keeping history in the file, comments should be used for 
commenting about the code. Best practice is to use a revision control 
system like hg, but if you're not up to that at least delete the dead 
code before posting.

When running into a problem with subprocess, your first step should be 
to *exactly* duplicate the successful command:

dnssec-signzone -e2018033000 -p -t -g -k Ktest123.com.ksk.key -o
  test123.com test123.com.external Ktest123.com.zsk.key


So you should try running that from subprocess:

subprocess.call([
'dnssec-signzone', '-e2018033000', '-p', '-t', '-g', 
'-k', 'Ktest123.com.ksk.key', '-o', 'test123.com', 
'test123.com.external', 'Ktest123.com.zsk.key',
])


and see if it still works. If it still does not work, that strongly 
suggests a problem with the environment: you are running it as the wrong 
user, in the wrong location, missing enviromnent variables or 
permissions. If it works in Python, then you can start replacing each 
constant argument with a calculated argument, *one argument at a time*, 
and see where you introduce the bug.



-- 
Steve
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor