RustPython / RustPython

A Python Interpreter written in Rust
https://rustpython.github.io
MIT License
18.69k stars 1.22k forks source link

error in the logic in python os module cwd output. #5038

Open ANVLISTENER opened 1 year ago

ANVLISTENER commented 1 year ago

C:\Users\username\Desktop>rspy ./hello.py .

C:\Users\username\Desktop>python ./hello.py C:\Users\username\Desktop

C:\Users\username\Desktop>

C:\Users\username\Desktop>rspy "C:\Users\username\Desktop\hello.py" C:\Users\username\Desktop

C:\Users\username\Desktop>

ANVLISTENER commented 1 year ago

hello.py:

import os

print(os.path.dirname(_file_))

hwoithe commented 12 months ago

What version of Python were you testing this with?

Depending on your version of Python, the __file__ attribute may be an absolute path or a relative path.

$ cat 5038.py
print(__file__)

$ docker run --network host -it --rm -v $(pwd)/5038.py:/tmp/5038.py python:3.8-slim /bin/bash -c "cd /tmp; python3 5038.py"
5038.py

$ docker run --network host -it --rm -v $(pwd)/5038.py:/tmp/5038.py python:3.9-slim /bin/bash -c "cd /tmp; python3 5038.py"
/tmp/5038.py

$ docker run --network host -it --rm -v $(pwd)/5038.py:/tmp/5038.py python:3.10-slim /bin/bash -c "cd /tmp; python3 5038.py"
/tmp/5038.py

$ docker run --network host -it --rm -v $(pwd)/5038.py:/tmp/5038.py python:3.11-slim /bin/bash -c "cd /tmp; python3 5038.py"
/tmp/5038.py

The behavior changed in Python 3.9 as documented here.

$ rustpython --version
RustPython 0.3.0

$ cp 5038.py /tmp/5038.py
$ cd /tmp
$ rustpython 5038.py
5038.py

It appears that the current RustPython version matches the Python 3.8 behavior.

A possible solution is to modify run_script to call run_code_string with an absolute path.

$ rustpython 5038.py
/tmp/5038.py

This would also cause the traceback to contain the absolute path.

Before patch:

$ pwd
/tmp
$ cat 5038-traceback.py
raise Exception("5038")

$ rustpython 5038-traceback.py
Traceback (most recent call last):
  File "5038-traceback.py", line 1, in <module>
    raise Exception("5038")
Exception: 5038

After patch:

$ rustpython 5038-traceback.py
Traceback (most recent call last):
  File "/tmp/5038-traceback.py", line 1, in <module>
    raise Exception("5038")
Exception: 5038

$ python3 --version
Python 3.10.12
$ python3 5038-traceback.py
Traceback (most recent call last):
  File "/tmp/5038-traceback.py", line 1, in <module>
    raise Exception("5038")
Exception: 5038

I'm sure this solution will require more thought and testings.

ANVLISTENER commented 12 months ago

hi hwoithe,

The python version is python 3.11 and the rustpython is RustPython 0.2.0.

Kindly help,

 Thank you.  

Regards ,

ANVLISTENER