Python: What does the following code do? - python

Can someone please explain to me piece by piece, what the following does? My code won't run and this part was provided. I've tested all of my code in iPython notebook and everything works, so I don't know if the problem is because of this block below.
def main():
args = sys.argv[1:]
if not args:
print 'usage: [--summaryfile] file [file ...]'
sys.exit(1)
summary = False
if args[0] == '--summaryfile':
summary = True
del args[0]
# ... my code ....
Update: I tried to do as Simon suggested. I opened up iPython and typed the following in the command line:
ipython 'assignment.py' --summaryfile
I tried variations of this and I keep getting a syntax error.
How do I run this?
Am I restricted to iPython only?

It basically checks to see if --summaryfile has been passed as an argument when you run the script
If no arguments have been passed, then it will print a line telling you how to use the script and then exit. summary is now set to false
If --summaryfile has been passed, then it will set summary = True and continue running the rest of your code
I'm not sure that you can enter arguments like that in ipython, so presumably your code will always exit because it doesnt find any arguments
EDIT:
For some reason I automatically associated ipython with ipython notebook. You can pass arguments with ipython. See here:
How to pass command line arguments to ipython
In your case, try adding --summaryfile as an argument when you run your script through ipython
If you're running this from ipython notebook, there are a couple of things you can try:
Remove that section of code and just set summary = True. The rest of your code should run, but without seeing everything its hard to say what impact this may have on the rest of your code
You can save your script as a python .py file, and use ipython magic to run the code from within notebook. You can pass arguments when you're running that script from within notebook. Check this: https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-run
If you have all the code in a regular .py file (outside of a notebook) you can run and pass an argument using the command line. Navigate to the directory where the script file is and run ipython filename.py --summaryfile

A very rudimentary command line argument parser.
It checks for the command line except the executable's name itself (sys.argv[1:]). If it's empty, dump help message and fail. If the first argument is "--summaryfile", set some flag.

Related

Python notebook use return value from running a script

I am using a notebook (in Google Colab) in python 3 and really need to execute some python2 code with some data that is generated in my notebook !
So what I did was
Generate the data in my cells AND save it to a file (data.txt)
Write a python 2 script (myScript.py) with a main() function that parses the file from sys.argv[1] into data and than calls my python2 functions and do all the stuff then it ends with return results (which is a dictionary)
In my notebook I run
!python2 myScript.py ./data.txt
(They are of course all in the same directory)
The command runs with no errors but no output ! How do I catch the results that are returned in a variable that I could use later ?
Not important but could be helpful :
Is there a better way to actually achieve what I am willing to achieve ?
Thanks to #Manuel's comment on the question, I figured out this solution and it worked :
In myScript.py, I changed return results by sys.stdout.write(json.dumps(results))
In my notebook, I changed the cell that executes the script to this:
results = !python2 test_langdetect.py ./tmp_comments.txt
myVar = json.loads(results[0])
Of course you need to import json

Python script requires input in command line

I'm new to python and I'm attempting to run a script provided to me that requires to input the name of a text file to run. I changed my pathing to include the Python directory and my input in the command line - "python name_of_script.py" - is seemingly working. However, I'm getting the error: "the following arguments are required: --input". This makes sense, as I need this other text file for the program to run, but I don't know how to input it on the command line, as I'm never prompted to enter any input. I tried just adding it to the end of my command prompt line, but to no avail.
Does anybody know how this could be achieved?
Thanks tons
if you pasted the code here that would help but
the answer you are most likely looking for is commandline arguements.
If I were to guess, in the command line the input would look something like:
python name_of_script.py "c:\thefilepath\totheinputfile" {enter}
{enter} being the actually key pressed on the keyboard and not typed in as the word
Hopefully this starts you on the right answer :)
Without reading your code, I guess if
I tried just adding it to the end of my command prompt line, but to no avail.
it means that you need to make your code aware the command line argument. Unless you do some fancy command line processing, for which you need to import optparse or argparse, try:
import sys
# do something with sys.argv[-1] (ie, the last argument)

When running python files in terminal, do return commands not get executed?

I am trying to understand how running a python file in terminal vs running it via IDLE, for instance, may change the way the code is interpreted. I didn't think there would be any difference, but I've been noticing that any "Return" commands in the code get ignored when the code is run on the mac terminal. Why is this the case?
For example, take a code as simple as the following:
def talk(arg):
return arg
talk("Hello!")
Now if I run this in terminal, I would expect it to print out "Hello!", because it would run the function talk on the given arg "Hello!" and return it. I do get the desired result if I change the last line to print talk("Hello!") then it works.
The commands do get executed, but unlike in the REPL, return values in a script are not automatically printed. You will need to use print/print() in order to actually get any output.

How can I add a command to the Python interactive shell?

I'm trying to save myself just a few keystrokes for a command I type fairly regularly in Python.
In my python startup script, I define a function called load which is similar to import, but adds some functionality. It takes a single string:
def load(s):
# Do some stuff
return something
In order to call this function I have to type
>>> load('something')
I would rather be able to simply type:
>>> load something
I am running Python with readline support, so I know there exists some programmability there, but I don't know if this sort of thing is possible using it.
I attempted to get around this by using the InteractivConsole and creating an instance of it in my startup file, like so:
import code, re, traceback
class LoadingInteractiveConsole(code.InteractiveConsole):
def raw_input(self, prompt = ""):
s = raw_input(prompt)
match = re.match('^load\s+(.+)', s)
if match:
module = match.group(1)
try:
load(module)
print "Loaded " + module
except ImportError:
traceback.print_exc()
return ''
else:
return s
console = LoadingInteractiveConsole()
console.interact("")
This works with the caveat that I have to hit Ctrl-D twice to exit the python interpreter: once to get out of my custom console, once to get out of the real one.
Is there a way to do this without writing a custom C program and embedding the interpreter into it?
Edit
Out of channel, I had the suggestion of appending this to the end of my startup file:
import sys
sys.exit()
It works well enough, but I'm still interested in alternative solutions.
You could try ipython - which gives a python shell which does allow many things including automatic parentheses which gives you the function call as you requested.
I think you want the cmd module.
See a tutorial here:
http://wiki.python.org/moin/CmdModule
Hate to answer my own question, but there hasn't been an answer that works for all the versions of Python I use. Aside from the solution I posted in my question edit (which is what I'm now using), here's another:
Edit .bashrc to contain the following lines:
alias python3='python3 ~/py/shellreplace.py'
alias python='python ~/py/shellreplace.py'
alias python27='python27 ~/py/shellreplace.py'
Then simply move all of the LoadingInteractiveConsole code into the file ~/py/shellreplace.py Once the script finishes executing, python will cease executing, and the improved interactive session will be seamless.

Python (windows) will open files from command line, but not from a script launched from eclipse

I'm pretty new to writing python for windows (linux is no problem), and am having problems getting python to recognize files when running scripts, though it behaves fine in the command line
What am I doing wrong here?
def verifyFile(x):
#
return os.path.isfile(x)
This will return true (with a valid file, of course) when called from the python command line, but when I run the script from eclipse, or launch it from windows, it ALWAYS returns false. Any thoughts on why this is?
I've tried passing pathnames like this:
D:\Documents and Settings\BDE\Desktop\cdburn.jpg
and like this:
D:/Documents and Settings/BDE/Desktop/cdburn.jpg
I've changed sys,argv[0] to ''
I've tried this:
def verifyFile(x):
#
try:
f = open(x, 'r')
f.close()
return True
except:
return False
and am getting no love!
Any help would be appreciated.
Thanks
Blake
There is not really enough information here to debug your issue, but I have a suspicion.
Try adding the line
print sys.argv
to the start of your code, and see what the actual arguments that are being passed in to your program. I have a feeling that you will find the the filename D:\Documents and Settings\BDE\Desktop\cdburn.jpg is being split into 3 separate arguments, D:\Documents, and, Settings\BDE\Desktop\cdburn.jpg. If so, you need to quote any filename that has spaces in it.

Categories

Resources