-
-
Notifications
You must be signed in to change notification settings - Fork 31.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
argparse.FileType for '-' doesn't work for a mode of 'rb' #58364
Comments
If an argument of '-' is handled by argparse.FileType, it defaults to sys.stdin. However a mode of 'rb' is ignored, the returned file object does not work with raw bytes. |
Yes, the problem is in FileType.__call__ - the handling of '-' is pretty simplistic. Patches welcome. |
Roger that. I'll start on a patch for this in a month or two if all goes well. |
Steven, patch attached. I lost steam in the unittests with all the meta, suffice it that the names match the file descriptors of the stream sources. i.e. FileType('rb') would give a file with name=0, and so forth. My chosen method also allows other mode flags as well as custom bufsizes. |
I don't know how if this is the perfect solution but it keeps the program from crashing. 1154c1154,1157
1156c1159,1162
|
The fix looks right, but we definitely need a test. I tried to write one, but I'm not sure how to do this properly given how test_argparse redirects standard input and output (so that fileno() doesn't work anymore). I've attached my current (failing) attempt to test this. |
A related issue http://bugs.python.org/issue13824 I proposed a FileContext class that returns a `partial(open, filename,...)' context object. The issues of how to deal with stdin/out are similar. |
There are a couple of complications to using 'fileno'. We probably don't want to close 'sys.stdin' or 'sys.stdout' (not even if they are redirected to other files?). That means using:
'closefd', on the other hand, has to be True for string file specifications. But in 'test_argparse.py', 'sys.stdout' is redirected to an 'io.StringIO'. This has many of the same features as an open file, but 'fileno' is not implemented. So the TypeFile probably needs to make an exception for this case. I don't how this will play with a 'BytesIO' for 'wb' cases. |
Nosy-ing myself since I just ran into it. Annoying issue that precludes from using argparse's builtin '-' recognition for reading binary data. I'll try to carve some time later to look at the patches. |
The patch looks reasonable? Is the only remaining problem with crafting the test? |
[sorry, the first question mark shouldn't be - the patch indeed looks reasonable to me] Steven - how about launching a subprocess for stdin tests to avoid weird issues? |
I fixed the tests to work with Steven patch. Also changed the patch to open sys.std{in,out} with closefd=False. I changed the 'io.StringIO' that we redirect the stdout, stderr to. Now the 'StdIOBuffer' return the real stdout,stderr when '-' is passed to FileType. This was already done in the 'stderr_to_parser_error' function previously after the call to 'parse_args'. |
Pinging as mentioned in the devguide. |
This is why I stopped contributing to Python. |
The problem with the argparse backlog is that the original author of the module is too busy with other things. And no one has stepped into his shoes. There are people with experience in apply patches, and people who know the argparse code well, but few, if any with both skills (and/or the time to invest in this module). In addition the module has some serious backward compatibility issues. I know of several patches that were applied, and then withdrawn because of unforseen (or at least untested) compatibility problems. While I commented earlier, I don't recall testing it. I just tried it now, and ran into problems - until I realized this isn't compatible with Python2.7. Py3 is the development world, but there's still a lot of PY2 use (e.g look at Stackoverflow argparse questions). On SO if people have problems with FileType, I often recommend that they just accept the filename, and take care of opening it themselves. To raise the attention to this patch I'd suggest
|
Hi paul thanks for looking into this. First are you sure this is a bug in python 2? If so I will happily port this patch once it is reviewed. |
The problem with Python2.7 is that 'open' does not take 'closefd', or any of the other parameters that were added for Python3. open(name[, mode[, buffering]]) 'rb' may make a difference on Py2 on Windows, but I haven't done any work in the environment in a long time. I wasn't aware of that other issue. Some core Python developers have participated in that one. I suspect a lot of the discussion is beyond my level of expertise. I once wrote that I thought 'FileType' was included primarily as an example of a 'type' factory. Something users could copy and extend for their own use. Bethard corrected me, saying that it was meant for quick-n-dirty script uses, ones with an input file, output file and a few options. In a bigger scripts, the users are encouraged to open/close files in 'with' contexts. See http://bugs.python.org/issue22884 and the issues I reference there. |
As we talk here about stdin and stdout which we don't want to close I think this issue is irrelevant to python2. In any case the patch in issue bpo-13824 cover that problem. |
This issue is relevant to Python 2 on Windows since you need to disable the EOL conversion if you're trying to receive binary data on stdin. See: http://stackoverflow.com/questions/2850893/reading-binary-data-from-stdin |
Bumped in this bug yesterday, sadly a script working (by chance) in Python2 doesn't work in Python3 because of this bug. |
I want to see this fixed in python3.x as well, please :) the patch should be the same |
What is the problem with using the patch by moritz (https://bugs.python.org/issue14156#msg162342) and change the unit test to this: class TestFileTypeWB(TempDirMixin, ParserTestCase):
...
successes = [
...,
('-x - -', NS(x=sys.stdout.buffer, spam=sys.stdout.buffer)),
] and respectively for stdin? |
The biggest problem, as paul.j3 says, is to get someone from core to review the argparse issues. I am currently planning to make argparse one of my foci in a sprint we are doing at the beginning of September, so there is some hope.... Any reviews/testing people do on argparse patches between now and then will be helpful. |
I just hit this bug. Would the proposed patch get any more attention if submitted as a pull request? |
It's been sometime since I looked at this issue. The main sticking point is passing unittests, and ensuring that there are no backward compatibility issues. But, since FileType is a standalone class, anyone could put a corrected version in their own workspace without modifying their stock version. The 'type' parameter is designed for this kind of flexibility - it accepts any callable, whether a function, or a class with a __call__ method. |
The solution with fileno() is clever, but as was mentioned before, it doesn't work if stdin or stdout are not real files, but something like StringIO. It is not that in common use of argparse for parsing arguments in scripts they are redefined, but argparse can be used in uncommon environments, for example for emulating command line in the environment like IDLE which redefines standard streams. And I'm sure this will break third-party tests which main() with patched stdin/stdout for testing CLI. The initial solution proposed by Moritz is more reliable, although it doesn't fix an issues with closing stdin/stdout. But this is a different issue at all. |
Serhiy: To be clear, Moritz's patch won't work if stdin/stdout are io.StringIO or the like either, since StringIO lacks a buffer attribute. Personally, I'm content to:
I'm going to convert Moritz's proposal to a PR and hope I can get core developer approval for it. |
I've created PR13165 to address this bug. It's 99% test updates; the actual code changes to argparse.py are trivial and should be equally trivial to review. The only functional change beyond Moritz's proposal is that I added support for having accepting '-' when the mode string uses 'a' or 'x' instead of 'w'; for sys.stdout, they're all effectively equivalent ('x' is trying to prevent stomping an existing file, which borrowing sys.stdout won't do, and sys.stdout is already more closely equivalent to mode 'a' in any event). No working code should break as a result of that change (passing 'a' or 'x' previously just caused FileType to exit immediately with a ValueError, which in turn caused parse_args to kill the program, which I'm assuming isn't considered a valuable "feature"). In addition to testing binary mode with argument '-' properly, I also added complete test cases for mode 'x' and 'xb' (for all arguments, both file names and '-') since we had no such tests, and ensuring exclusive creation mode behaves correctly is fairly important. |
I just ran into this issue on Linux when piping a binary file to stdin resulted in a UnicodeDecodeError while trying to read a byte from the stream. Passing /dev/stdin is a workaround that does not require modifications to an application. As for the proposed PR 13165, I'd suggest to gracefully fallback to normal stdout/stdin if the buffer is not available. That approach is also followed in the fileinput module, and takes care of the note for library developers in the documentation at https://docs.python.org/3/library/sys.html#sys.stdin Not feeling particular strong about the graceful handling, but I hope that the test code can be simplified in that case. |
Nosying myself; this affects 3.9 and 3.10 as well. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: