问题
Using Pycharm to write a python script for loading and formatting a fixed width file I'm getting different results when I run the script in terminal (within Pycharm or locally) and when using the run option in Pycharm. Any reason why this is the case and which is correct?
with open('uk_dcl_mrg.txt', 'rb') as f:
ct = 0
for line in f:
ct += 1
#### OUTOUT ####
for i in layout: ## Loop to create dictionary
headerdict[i[0]] = line[i[1]:i[2]]
if (headerdict['CORP-STATUS-IND'] == "\x9f"):
headerdict['CORP-STATUS-IND'] = '0'
elif headerdict['CORP-STATUS-IND'] == '?':
headerdict['CORP-STATUS-IND'] = '1'
else:
headerdict['CORP-STATUS-IND'] = '2'
print(headerdict)
if ct >= 6:
break
Output in Terminal
'CORP-STATUS-IND': '0',
Output in the run option of Pycharm
'CORP-STATUS-IND': '2',
The terminal output is what I am expecting.
回答1:
I'm usually not answering when I'm not sure but here I'm pretty sure:
You're probably running 2 different interpreter versions. Python 2 in your console, and Python 3 in PyCharm.
Confirm it by inserting the following line in your script:
print(sys.version)
The problem is this line:
with open('uk_dcl_mrg.txt', 'rb') as f:
since you're opening the file as binary, in Python 3, lines are binary, not string, so comparing them to string always fails.
>>> b'\x9f'=='\x9f'
False
>>> b'\x9f'[0]
159
>>> '\x9f'[0]
'\x9f'
In Python 2, the lines are of str
type regardless of the file open mode, which explains that it works.
Fix your code like this:
with open('uk_dcl_mrg.txt', 'r') as f:
It will work for all versions of python. But I recommend that you drop Python 2 unless you're tied to it and install Python 3 by default.
回答2:
Honestly, I'd just stick with the terminal. The problem with IDEs is that sometimes the don't interpret the code directly, and/or through the official "python interpreter." In addition, there are so many settings and other arguments that can be run alongside your code that could theoretically edit the results. Furthermore, your interpreter could still be interpreting via an older version of python. Now, to be honest with you, most of this is unlikely, but it's the only plausible reason I see. Personally, I'd recommend just using something like nano in the terminal to code (that's what I do), and then just running your code straight from the terminal. But, if you still like the IDE, than maybe just use the IDE for syntax highlighting, but still run your code from the terminal?
来源:https://stackoverflow.com/questions/41146596/pycharm-terminal-and-run-giving-different-results