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)
Related
I figured out the zip code in same line out. It's sys.argv[1], I had other code I neglected to comment out when trying out [1] that gave me the error. All I need help with now is getting weather.py to run without having to call the whole file path.
I will preface with I'm not very experienced with python and may get certain names wrong or think something might work that obviously doesn't, bear with me I tried to word this to make as much sense as possible.
So I need to run a program using the command line. The program is complete and 100% functioning when ran in PyDev. The program is called weather.py, and what needs to trigger it in cmd is
python weather.py (5 digit zip)
I cannot get the program to run using just 'python weather.py' first off. I have added C:\python27 to PATH as well as C:\python27\python.exe (not sure if that does anything). Getting the .py to run via those two keywords doesn't seem to work with what I've tried. I also need to be able to add a zip code to the same line to trigger the program. I was told about
zipcode = sys.argv[0]
to allow the zip code to be automatically initialized as a variable, but I get
IndexError: list index out of range
when I run the program using
python C:\python27\weather.py
I tried replacing 0 with 1 or 2 because I'm unfamiliar with .argv but neither of those worked either. Any help getting the program to run using just python weather.py OR getting the zip code input to function on the same line is greatly appreciated.
Make sure you import sys in your code.
import sys
zipCode = sys.argv[1]
and actually provide an argument
EDIT:
For clarity, if sys was not imported, you would get NameError and not an IndexError. Additionally, when passing args in from the command line, the indexing actually begins at 0 where sys.argv[0] is always the program name and the provided args begin at 1. So, in this case, the zip code would be at sys.argv[1]
EDIT2:
variable name to avoid using reserve words :)
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.
I got a python file which is a code that I developed. During his execution I input from the keyboard several characters at different stages of the program itself. Also, during the execution, I need to close a notepad session which comes out when I execute into my program the command subprocess.call(["notepad",filename]). Having said that I would like to run this code several times with inputs which change according to the case and I was wondering if there is an automatic manner to do that. Assuming that my code is called 'mainfile.py' I tried the following command combinations:
import sys
sys.argv=['arg1']
execfile('mainfile.py')
and
import sys
import subprocess
subprocess.call([sys.executable,'mainfile.py','test'])
But it does not seem to work at least for the first argument. Also, as the second argument should be to close a notepad session, do you know how to pass this command?
Maybe have a look at this https://stackoverflow.com/a/20052978/4244387
It's not clear what you are trying to do though, I mean the result you want to accomplish seems to be just opening notepad for the sake of saving a file.
The subprocess.call() you have is the proper way to execute your script and pass it arguments.
As far as launching notepad goes, you could do something like this:
notepad = subprocess.Popen(['notepad', filename])
# do other stuff ...
notepad.terminate() # terminate running session
First off I looked in the documentation and found this:
http://www.tutorialspoint.com/python/python_command_line_arguments.htm
And then I also found this:
how to execute a python script file with an argument from inside another python script file
I am using pycharm 2.7.3 and when I try to run my script I get and error (the error is not pycharm related). THe only way around this error I have found out to be is to run the script through the windows PowerShell with a couple of "arguments" (is that what its called?)
The code that follows is what makes up my script, temp.py
from sys import argv
# this what the Ide fails to run
scripts, first, second, third = argv
print "The script is called:", scripts
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
Next is what I types into the powershell
NOTE: The above code is temp.py
python temp.py first 2nd 3rd
1) What are those pieces of text called that appear after the "python temp.py", is it arguments?
2) Is it possible to run the code with the so called arguments in the IDE (I am using pyCharm)
3) If '2)' = True, how so?
1) What are those pieces of text called that appear after the "python temp.py", is it arguments?
Yes, the things you pass after temp.py on the shell are called "arguments", or "command line arguments". Sometimes they're called "parameters" instead, sometimes with the word "actual" as a prefix.*
And note that temp.py and all of its arguments are themselves arguments of python.
The sys.argv variable that you're using specifically gives you:
The list of command line arguments passed to a Python script…
2) Is it possible to run the code with the so called arguments in the IDE (I am using pyCharm)
Yes. Almost every IDE has a way to do this.
3) If '2)' = True, how so?
Read the PyCharm docs for details, but IIRC, they're part of the "run/debug configuration"; when you use the "Edit Configurations" command and edit one, there's a box labeled "Script Parameters" for you to enter the arguments.
* Using "parameters" is a bit misleading. Speaking technically, using the terminology Python uses for function calling, you should say that your script has a single parameter, a variable-positional parameter which gathers all of the arguments used to call it, which you can access as sys.argv. But as you can guess, nobody actually says things that way. If someone says "command line parameters" or "script parameters", they mean "the things in sys.argv".
I want to call a program multiple times from a python code, and save the output of that program in a text file. My first problem right now is just calling the other code. I have to redirect to a different directory and call ./rank on output.txt. This is how Im trying to do it:
TheCommand = "~/src/rank-8-9-2011/rank output.txt"
os.system(TheCommand)
but im getting a parsing error.
[Parsing error on line ]Unknown error: 0
Im running python2.7 on Mac OS 10.5.8. Im not sure what the problem is. I also tried using subprocess:
subprocess.call(["~/src/rank-8-9-2011/rank", "output.txt"])
This does not find the directory (I have a feeling Im using the subprocess incorrectly), but I dont know what is wrong with the os.system.
the name of the program in the first argument to subprocess.Popen must not contain ~ as it doesn't pass the string to the shell for processing (which like always using parameterized queries in sql, protects one from string injection attacks, e.g. if instead of output.text one had ;rm -rf /, the system version would run rank and then run rm -rf . but the subprocess.Popen would only have rank open a file named ;rm -rf .), so one should expand it by calling os.path.expanduser:
subprocess.Popen([os.path.expanduser('~/src/rank-8-9-2011/rank'), "output.txt"])
although it is possible to turn shell processing on by passing shell=True, it is not recommended for the aforementioned reason.
you should try http://docs.python.org/library/os.path.html#os.path.expanduser
import os.path
subprocess.call([os.path.expanduser("~/src/rank-8-9-2011/rank"), "output.txt"])
I'm fairly certain your parsing error is coming from rank, not from your os.system command, as nothing there looks weird. What happens if you run rank manually?
subprocess seems to have a problem with '~', although I'm not immediately sure why. Put the full path and it should work (although you'll likely get that parsing error if it is indeed a problem with rank).