I have many python files all with the same variable names but different values. Something like this would be in one: var_one = 'happy' var_two = '2345' var_three = '-24.24' var_four = 'Chocolate'  I need to write a Python script that can read these files and when I ask for var_one it returns happy. If I ask for var_two it returns 2345 and so on and so forth. Right now I have a python two compliant toolbox that does this using something along the lines of: for fname in myfile:     d = toolbox.datafile(fname)     my_mood = d['var_one']     number  = d['var_two']     decimal = d['var_three']     candy   = d['var_four']  And then printing my_mood would print out happy. However, this toolbox is not python 3 compliant and I did not make it so I would like to know if there is an easy built in toolbox that can accomplish this task. Thanks in advance EDIT** The importing method seems like it will be the most helpful for answering this question. The only problem that I have now with it is that I do not know how to import the files. To explain further I am going to be parsing the command-line arguments and one of the arguments will be the location of said file that we want to import. What is the syntax to import that? I have an args.file that equals &lt;home/myname/python/myfile.py&gt; So how would I import args.file?
7325
How can I load a Python module given its full path? Note that the file can be anywhere in the filesystem, as it is a configuration option.
2534
I am trying to calculate field test2 with only the numeric values from a string field test. The entire script is like:    def makestr(test)      list=[]      for s in test:          if s.isdigit():              list.append(s)      for a in list:          str=''.join(list)     But I keep getting an error:    Any ideas?
11740
I'm running tests of a variable-size-and-contents test set. Data files are added and removed frequently. I'm looking for an automated way of gathering a file list.  All files are in subdirectories of D; I need the full directory and name added to a text file. However, I only need those files that have a "paired" file, which has the same filename but a different extension (so... different filename, but in a structured way). So, if there is a MyFileName.A and MyFileName.B, then I want D/.../MyFileName added to the file list.  There are .A files without .B files, but no .B files without .A files. If a .A has a .B file, then both files are in the same directory.   Any advice?
100065
I have a directory with several hundred csv files whose filenames start with two digits {01..84}. Several hundred >> 84, so obviously some filenames start with the same prefix. I wish to concatenate the files whose filenames start with the same prefix. Here's what I've got:  #!/bin/bash for i in {01..84}; do         #declare array to store files with same prefix         declare -a files=()         echo "Processing $i"         for j in `ls $i*.csv`; do                 #add files with same prefix to array                 files=("${files[@]}" "$j")         done             #cat first file including header with the rest of the files without the headers          cat &lt; ${files[@]:0:1} &lt;(tail -n+2 ${files[@]:1}) &gt; "$i".csv done    So far so good ... only, it grinds to a halt at $i=22 halfway through (repeatable error), and pollutes the output files with blank lines and headers like "==> 19XXX.csv &lt;==" (without quotes).   What should I change in the code to just get a nice clean csv file for each prefix without the script crashing? Are there any precompiled bash utilities that I can call to do any of this quicker and easier?
1384
Say, I have a script that gets called with this line: ./myscript -vfd ./foo/bar/someFile -o /fizz/someOtherFile  or this one: ./myscript -v -f -d -o /fizz/someOtherFile ./foo/bar/someFile   What's the accepted way of parsing this such that in each case (or some combination of the two) $v, $f, and  $d will all be set to true and $outFile will be equal to /fizz/someOtherFile?
58840
I have a model that passes a variable to a python script. The script uses that variable to query some directories and return a list of paths. What I want to know is:    How can I then use each of those paths as the parameter in a subsequent operation? Is the bridge between python and ModelBuilder a one-way street?
75539
I have a text file with tab-separated columns which I'd like to process using awk. Here's an example of such a file: size=1\tname=foo\tweight=1.2 weight=2.5\tname=bar\tsize=2  What I want to achieve is to normalize the numeric value in columns whose content is like $field_name=&lt;number&gt; to four decimal places and keep the rest as is. Here, $field_name is a shell variable that is passed to awk and I'd like to use its value inside a regex. Here's a snippet (which is not working of course). I'm particularly interested in fixing line #5 in the following awk script and not solutions using other tools, such as sed, perl, python, etc. $ cat &quot;${file}&quot; \                                       # 1     | awk -F &quot;\t&quot; -v field_name=&quot;${external_var}&quot; '     # 2       {                                                 # 3         for (i = 1; i &lt;= NF; i++) {                     # 4           if ($i ~ /$field_name=[0-9]*.?[0-9]+/) {      # 5             split($i, kv, &quot;=&quot;)                          # 6             $i = sprintf(&quot;%s=%.4f&quot;, kv[1], kv[2])       # 7           }                                             # 8         }                                               # 9         print $0                                        # 10       }'
12267
I am making the check for update script for my theme  I have 2 text files. First one is called "current.txt" and contains the current version. There is 4.1.1 string in that text file.  Second one is called "latest.txt" and contains the latest version. There is 4.2 string in this text file.  So here is the code  echo "Checking update"; x=$(cat ./current.txt) y=$(cat ./latest.txt) if [ "$x" -eq "$y" ] then        echo There is version $y update else        echo Version $x is the latest version fi   What it mean is if current.txt is NOT the same with latest.txt then it will say "there is version 4.2 update". If not, it will say "version 4.1.1 is the latest version"  But when I try to run it. I get this error  Checking update ./test.sh: line 4: [: 4.1.1: integer expression expected Version 4.1.1 is the latest version   So what am I doing wrong with this?
2525
My  has failed me.  In Python, are the following two tests for equality equivalent?  n = 5 # Test one. if n == 5:     print 'Yay!'  # Test two. if n is 5:     print 'Yay!'   Does this hold true for objects where you would be comparing instances (a list say)?  Okay, so this kind of answers my question:  L = [] L.append(1) if L == [1]:     print 'Yay!' # Holds true, but...  if L is [1]:     print 'Yay!' # Doesn't.   So == tests value where is tests to see if they are the same object?
10618
I am trying to enumerate a range of integers using a variable but having some trouble.  When I type  echo {1..5}   I get  1 2 3 4 5   However, when I type a variable, I am unable to get the enumeration.  For example  $ num=5 $ echo {1..$num} {1..5}   I am stumped as to why the result is not the same.  I have tried using quotes and that has not helped either.  Can someone help or explain?
43815
So I found this python script on another post here and was trying to adjust it for my needs.  I'm a very novice python user so I'm struggling with how to modify the script.  I have a Feature Class stored in a feature Dataset that I want to search a field for duplicate values and populate a new field with Y for duplicate or N for none.  The below script is what I found that looks like it will work once I find a way to drill down into my file geodatabase.          from arcpy import *          inShapefile = pointsShapefile          checkField = "xyCombine"         updateField = "dplicate"         #List of values found once         occursOnce = []        #list of values found twice         occursTwice = []       cursor = da.SearchCursor (inShapefile, [checkField])           for row in cursor:           #Check value is not null        if row[0]:     #If not already found to occur twice, proceed     if not row[0] in occursTwice:         #If hasn't occured once yet         if not row[0] in occursOnce:             #Add to occurs once list             occursOnce.append (row[0])         #If value has already been found once         else:             #Add to occurs twice list (duplicates)             occursTwice.append (row[0])     del cursor       cursor = da.UpdateCursor (inShapefile, [checkField, updateField])      for row in cursor:       #Check value is not null         if row[0]:            #check if value in occursTwice list (i.e. is duplicate)     if row[0] in occursTwice:         row[1] = "Y"     else:         row[1] = "N"     cursor.updateRow(row)    del cursor
69637
i am writing a script in bash and I would like to give the two numbers in the brackets, x and y to be precise, as variables.  I wrote the script this way:  echo "x?" read x echo "y" read y  for i in {$x..$y}   but it does not work.  How could I set it up to make it function?  Thanks a lot in advance.
42221
A friend asked me last week how to enumerate or list all variables within a program/function/etc. for the purposes of debugging (essentially getting a snapshot of everything so you can see what variables are set to, or if they are set at all). I looked around a bit and found a relatively good way for Python:   #!/usr/bin/python                                                                                                                                                                                                                            foo1 = "Hello world" foo2 = "bar" foo3 = {"1":"a",         "2":"b"} foo4 = "1+1"  for name in dir():     myvalue = eval(name)     print name, "is", type(name), "and is equal to ", myvalue   which will output something like:   __builtins__ is &lt;type 'str'&gt; and is equal to  &lt;module '__builtin__' (built-in)&gt; __doc__ is &lt;type 'str'&gt; and is equal to  None __file__ is &lt;type 'str'&gt; and is equal to  ./foo.py __name__ is &lt;type 'str'&gt; and is equal to  __main__ foo1 is &lt;type 'str'&gt; and is equal to  Hello world foo2 is &lt;type 'str'&gt; and is equal to  bar foo3 is &lt;type 'str'&gt; and is equal to  {'1': 'a', '2': 'b'} foo4 is &lt;type 'str'&gt; and is equal to  1+1   I have so far found a partial way in PHP (courtesy of ) but it only lists all variables and their types, not the contents:   &lt;?php // create a few variables $bar = 'foo'; $foo ='bar'; // create a new array object $arrayObj = new ArrayObject(get_defined_vars()); // loop over the array object and echo variables and values for($iterator = $arrayObj-&gt;getIterator(); $iterator-&gt;valid(); $iterator-&gt;next())         {         echo $iterator-&gt;key() . ' =&gt; ' . $iterator-&gt;current() . '&lt;br /&gt;';         } ?&gt;   So I put it to you: how do you list all variables and their contents in your favorite language?    Edit by : I propose this question follows the spirit of a little "". If you do not agree, just edit and remove the tag and the link.
61612
I'm looking for a  way to convert numbers to string format, dropping any redundant '.0'   The input data is a mix of floats and strings. Desired output:  0   --> '0'  0.0 --> '0'  0.1 --> '0.1'  1.0 --> '1'  I've come up with the following generator expression, but I wonder if there's a faster way:  (str(i).rstrip('.0') if i else '0' for i in lst)   The truth check is there to prevent 0 from becoming an empty string.  EDIT: The more or less acceptable solution I have for now is this:  ('%d'%i if i == int(i) else '%s'%i for i in lst)   It just seems strange that there is no elegant way to handle this (fairly straightforward) case in python.
99975
How do I get a random  instance? It appears that the random module only returns floats which are a pita to convert to Decimals.
11099
I have the following file:  abcde kwakwa &lt;0x1A&gt; line3 linllll   Where &lt;0x1A&gt; represents a byte with the hex value of 0x1A. When attempting to read this file in Python as:  for line in open('t.txt'):     print line,   It only reads the first two lines, and exits the loop.  The solution seems to be to open the file in binary (or universal newline mode) - 'rb' or 'rU'. Can you explain this behavior ?
60659
I have a situation where I want to define a command that takes a variable number of arguments, where the number of arguments is known programmatically via a \count, and process the parameters in some way (say as if they are a list).  As an example, say I'd like to output the parameters as a comma-separated list.  \newcommand{\makecsv}[N]{#1, #2, ..., #N}   The code that I've come up with to do this kind of operation (in a generic-ish way) essentially takes a command, \csv and expands it recursively N times. \csv needs to know how to continue the recursion, and has some state that I'd like to thread through the recursion (rather than using \global).  \documentclass{report} \usepackage{etoolbox}  \makeatletter \newcommand{\ifzero}[3]{%   % #1: count   % #2: state for #3   % #3: macro to expand to   % - should take at least 2 parameters   % - ##1: count threaded through   % - ##2: macro state threaded through   \ifnum\c &gt; 0     \def\tmp@f##1##2##3{##1{##2}{##3}}%     \advance#1 -1%   \else     \def\tmp@f##1##2##3{)}% note closeparen here (could be param)   \fi   \tmp@f{#3}{#1}{#2}% } \makeatother  \newcommand{\csv}[3]{   % #1: count   % #2: separator state   % #3: string to concat   %    #2#3\ifzero{#1}{, }{\csv}% }  \newcommand{\makecsv}[1]{%   \ifzero{#1}{}{\csv}% }  \makeatletter \newcommand{\decl}[3]{%   % #1: decl id   % #2: decl symbol   % #3: # params   \csgdef{decl@#1}{#2}%   \global\expandafter\newcount\csname decl@#1@nparams\endcsname%   \csuse{decl@#1@nparams} #3\relax% }  \newcommand{\usedecl}[1]{%   \newcount\c   \c \the\csuse{decl@#1@nparams}   \csuse{decl@#1}(\makecsv{\c}% } \makeatother  % declare some interface routines \decl{foo}{FOO}{3} \decl{bar}{BAR}{4}  \begin{document} \usedecl{foo}{p1}{p2}{p3}\par \usedecl{bar}{p1}{p2}{p3}{p4}\par \end{document}   Is this a reasonable thing to do in 2e, or is there some sort of standard approach to this that is normally used?  Edit 1  It seems like my original MWE wasn't adequate to describe why someone might want this. I've updated the MWE with a use case. \decl allows authors to declaratively define a C-style function, and \usedecl allows the author to generate a use of the function, with its parameters bound to specific arguments.  This is similar enough to what I'm doing that it should help motivate the example.