How to know which file is calling which file, filesystem - python

How to know which file is calling which file in filesystem, like file1.exe is calling file2.exe
so file2.exe is modified,
and file1.exe is entered in log file.
winos
I have searched INTERNET but not able to find any samples.

In order know which file is calling which file you can use the Trace module
exp: if you have 2 files
***file1.py***
import file2
def call1():
file2.call2()
***file2.py***
def call2():
print "---------"
u can use it using console:
$ python -m trace --trackcalls path/to/file1.py
or within a program using a Trace object
****tracefile.py***
import trace,sys
from file1 import call1
#specify what to trace here
tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix], trace=0, count=1)
tracer.runfunc(call1) #call the function call1 in fille1
results = tracer.results()
results.write_results(summary=True, coverdir='.')

Related

How do I open another Python file within a file with a parameter/argument/variable attached?

I want to run another file from my main.py and also set the value of a variable in the main.py and "export it", so I can use it in the other file.
But I absolutely don´t know how to do that.
So that I can set a 'var = x[3]' in the main file and kinda "export" the variable into the file that I am opening like 'import otherfile.py(var = x[3])'
Thanks in advance
To import any variable from main file to otherfile you can use,
from main import*
Y = var
That's how you can set var in main.py file and import or use it in otherfile.py.
You can use sys.argv to get arguments if you run the file from the command line
so if you have the file:
import sys
print(sys.argv[0])
then open a command line and type python file.py hello it will print 'hello'.
As well, you can use os.system() to run command line functions from python
so your first file could be:
import os
var = 'test'
os.system(f"python otherfile.py {var}")
and otherfile.py could be:
import sys
print(sys.argv[0])
then if you run the first file, a python window will open and print 'test'.
Hope this was what you were looking for

I keep having a error when running the script. It keeps sending "name input_file is not defined"

I am trying to create a python def to unzip a few .gz files within a folder. I know that the main script works if it is not in the def. The script I have created is similar to others I have done but this one give me the error
File "unzip.py", line 24, in
decompressed_files(input_folder)
NameError: name 'input_folder' is not defined
I copied the script below so someone can help me to see where the error is. I haven't done any BioInformatics for the last couple of years and I am a bit rusty.
import glob
import sys
import os
import argparse
import subprocess
import gzip
def decompressed_files(input_folder):
print ('starting decompressed_files')
output_folder=input_folder + '/fasta_files'
if os.path.exists(output_folder):
print ('folder already exists')
else:
os.makedirs(output_folder)
for f in input_folder:
fastqs=glob.glob(input_folder + '/*.fastq.gz')
cmd =[gunzip, -k, fastqs, output_folder]
my_file=subprocess.Popen(cmd)
my_file.wait
print ('The programme has finished doing its job')
decompressed_files(input_folder)
This is done for python 2.7, I know that is old but it is the one that it is installed in my work server.
That's why when you call decompressed_files(input_folder) in the last line, you didn't define input_folder before. you should do it like this :
input_folder = 'C:/Some Address/'
decompressed_files(input_folder)

Python - Called Script is searching for a file in the Calling Script's directory

I have the following structure
C:\Users\dhiwakarr\workspace\BasicRegressionOnJoker\create&&bkp\script1.py
script1.py will call a function/method defined in script2.py which is located in
C:\Users\dhiwakarr\workspace\basics\script2.py
The problem is script2.py will make use of an XML File (create.xml) which is located in the same folder as script2.py. But when I call this method IN script2.py FROM script1.py. I get the following error,
execute: Error 0x304: Failed to read the input file[createsc.xml].
Traceback (most recent call last):
File "create&&bkp.py", line 19, in <module>
CreateSC.create()
My guess is that the called script (script2.py) is searching for this file in the calling script (script1.py). How do I make the method of script2.py called in script1.py make it search in its own directory ?
UPDATE
script1.sc
import subprocess,sys,getopt,codecs,re,string
import xml.etree.ElementTree as ET
sys.path.insert(0,r'C:\Users\dhiwakarr\workspace\basics')
import Login
import script2
#import script3
try:
#First call the login script to login
print('Login started')
Login.login()
print('Create Subclient')
script2.create()
....
script2.py
import subprocess,sys,os,inspect
from sys import stdout
from _winapi import NULL
def create():
'''
A text file with information about the Client,Storage Policy,Backupset,Subclient & Content of each subclient must be given as seen in sample-create.txt
'''
inputfile = r'C:\Users\dhiwakarr\workspace\create.txt'
finp = open(inputfile,'r')
path = str(os.getcwd())
print('Current Working Path is -- '+path)
for line in finp:
line=line.rstrip('\n')
....
# Creating the Subclient
subprocess.check_call(["C:\\Program Files\\CommVault\\Simpana\\Base\\qoperation.exe", 'execute', '-af', `'createsc.xml',` '-appName', "'File System'",'-clientName', client,'-backupsetName', bset, '-subclientName', scname, '-storagePolicyName', storagepolicy])
else:
See the line subprocess.check_call(["... it fails to read the XML.
The information given is sparse and more code would be helpful.
In general when calling a script from the command line, the base path will be the path, the shell is directed to not the path of calling.
To get information about where your script is looking for files, insert
print os.getcwd()
at the appropriate places (before open or file command). You need to have imported 'os' from the battery pack though.
Furthermore, to get better understanding of the underlying problem, using a
try:
f = open(f)
…
except IOError as e:
print "I/O error({0}): {1}".format(e.errno, e.strerror)
except:
print "Unexpected error:", sys.exc_info()[0]
raise
might give better understanding of the underlying problem.
your added code information:
Changes of sys.Path (.extend; .insert) will not change the directory for file I/O. sys.Path is directing the module loader only. Use os.chdir or relative paths for file I/O. Use the above print os.getcwd() method get further information about where your code is looking for the .xml file.

Python - create object of class from one package in different package

I started using Python few days back and I think I have a very basic question where I am stuck. Maybe I am not doing it correctly in Python so wanted some advice from the experts:
I have a config.cfg & a class test in one package lib as follows:
myProj/lib/pkg1/config.cfg
[api_config]
url = https://someapi.com/v1/
username=sumitk
myProj/lib/pkg1/test.py
class test(object):
def __init__(self, **kwargs):
config = ConfigParser.ConfigParser()
config.read('config.cfg')
print config.get('api_config', 'username')
#just printing here but will be using this as a class variable
def some other foos()..
Now I want to create an object of test in some other module in a different package
myProj/example/useTest.py
from lib.pkg1.test import test
def temp(a, b, c):
var = test()
def main():
temp("","","")
if __name__ == '__main__':
main()
Running useTest.py is giving me error:
...
print config.get('api_config', 'username')
File "C:\Python27\lib\ConfigParser.py", line 607, in get
raise NoSectionError(section)
ConfigParser.NoSectionError: No section: 'api_config'
Now if I place thie useTest.py in the same package it runs perfectly fine:
myProj/lib/pkg1/useTest.py
myProj/lib/pkg1/test.py
myProj/lib/pkg1/config.cfg
I guess there is some very basic package access concept in Python that I am not aware of or is there something I am doing wrong here?
The issue here is that you have a different working directory depending on which module is your main script. You can check the working directory by adding the following lines to the top of each script:
import os
print os.getcwd()
Because you just provide 'config.cfg' as your file name, it will attempt to find that file inside of the working directory.
To fix this, give an absolute path to your config file.
You should be able to figure out the absolute path with the following method since you know that config.cfg and test.py are in the same directory:
# inside of test.py
import os
config_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'config.cfg')

Passing command line argument to another file imported in Python

I have a python file (html2text.py) which gives the desired result when i pass command line argument to it i.e., in the following way:
python html2text.py file.txt
where file.txt contains the source code of a web-site and the result is displayed on the console...
I want to use it in another file (let say a.py) and store the result (which was getting printed on the console) in a string.
For this I need to first import the file (html2text.py) in my file (a.py). Can anyone tell me how do I proceed further...?
Good way is to create some API in your html2text.py. For example:
# html2text.py
def parse(filename):
f = open(filename)
# do the stuff
return output_string
def main():
import sys
print parse(sys.argv[1])
if __name__ == '__main__':
main()
Then you will be able to use it in your a.py:
import html2text # main() will not run
import sys
output = html2text.parse(sys.argv[1])
I think the best way is the reorganize a little your html2text.py file. Append the line like this to your file:
def main():
message = sys.stdin.readlines()
a = your_def(message)
if __name__ == '__main__': main()
Now you're sure, that when invoking the file from command line, everything will go fine. Moreover, if you have everything kept in functions and classes, you can now in your a.py
import html2text
and work on it already in a.py.

Categories