PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, August 24, 2022

[FIXED] How do I get the file path of python script within loaded module?

 August 24, 2022     module, python     No comments   

Issue

I wrote a module module.py that I import in various scripts. The module has a function that needs the file path of the script main.py that it was imported by and do something with it. How do I get this file path?

module.py

def main_file_path():
    print(way_to_acces_main_file_path)

is imported in

main.py

import module
module.main_file_path()

Running main.py should print the file path of main.py


Solution

The system argv always has the program name as the first element. This should work most of the time:

import sys
import os

path = os.path.abspath(sys.argv[0])
print(path)


Answered By - Keith
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing