How to type python file in cmd?
<p>I have completed a py file as follow:</p>

<pre><code>import re

file = open('/Path/text1.txt')

word = 'summer flowers'

try : 

   flag = 0

   for line in file :

       lines = line.lower()

       x=re.findall('.*'+word+'\s.*',lines)

       if len(x)&gt;0:

           flag =1

           print line

       else:

           flag = flag

   if flag == 0:

       print 'No match!'

except:

    print 'No enough arguments!'
</code></pre>

<p>I have saved above py file as test1.py. My question is that: How to type above code in the cmd line?</p>

<p>e.g. I hope to input the code:
" <strong>test1.py 'summer flowers', text1.txt</strong> " 
in the cmd to execute above code </p>

<p>where test1.py is the file name of the py file, 'summer flowers' is the key word I want to search and match in the txt file and text1.txt is the txt file name.</p>

<pre><code>import re
import sys 

file = sys.argv[2]
word = sys.argv[1]

try : 

   flag = 0

   for line in file :

       lines = line.lower()

       x=re.findall('.*'+word+'\s.*',lines)

       if len(x)&gt;0:

           flag =1

           printline

       else:

           flag = flag

   if flag == 0:

       print 'No match!'

except:

    print 'No enough arguments!'
</code></pre>

<p>Use <code>sys</code> to deal with command line stuff. <code>sys.argv</code> returns a list of the arguments from the command line and since you wanted to run it in cmd line use <code>python script_name.py keyword filename</code> don't need quotes for single words or commas. Also note <code>sys.argv[0]</code> is reserved for the file name so <code>sys.argv</code> returns <code>['script_name.py', 'keyword', 'filename']</code> if you ran the command above.</p>

<p>Edit: </p>

<p>Like the comment says if you want a phrase instead of a word you can use <code>quotes</code> in the commend line so: </p>

<p><code>python script_name.py "my phrase" filename</code></p>

<p>will return in <code>sys.argv</code> as <code>['script_name.py', 'my phrase', 'filename']</code></p>

python python-2.7 text-mining