How do I create a header file in python ?
I know the steps to do it in C++ but I don't know how to do it in python.
You can do something like this:
create a new python file (e.g.: pseudo_header) here you can add function, variables etc.
Example - in pseudo_header:
name = "Bob"
in your main.py do this:
import pseudo_header
print(pseudo_header.name) << "Bob"
pseudo_header.name = "John"
print(pseudo_header.name) << "John"
Python is not having header files like c++. Instead we import libraries here.
For example take below small piece of code.
import datetime
print datetime.datetime.now()
Output
2019-11-15 12:33:33.177000
Here we are importing library datetime. datetime.datetime.now() will give you the current date.
You can also import only a specific object instead of whole module. Like below.
from datetime import datetime
print datetime.now()
There is no need to define anything before code in python as we did in c++.
You just know about the syntax of the python it will be enough for beginner programming.
But if you want to use some extra libraries then you will need some importing.
Example
print("Hello World")
output
>> Hello World
Similarly you can define variables, do some conditional programming or define some loops etc.
Example
a = 5
if a != 5:
print("I am angry")
if a == 5:
print("I am happy")
output
>> I am happy
See there is no need to do any importing.
But if you want to use some libraries like. DateTime
import datetime
print datetime.datetime.now()
This library deals with date and time and anythings belongs to them.
That is python :)
What I usually do is create a separate library file with all function definitions and import this in the main script.
Let's say my library is called foo.py, which contains
import numpy as np
def side(area):
'''
Function to get length of the side of a square of a given area.
'''
assert (area > 0), 'Invalid input!'
return np.sqrt(area)
Then, in my main script, I just import the library and use the functions.
import numpy as np
from foo import *
area = 100
print (side(area)) # returns 10
May not be the best way but works for me.
Related
I want to import one specific line of code from one script into another. I don't want the new code to run the entire script just that one line. How do I do that?
e.g. from brcus import value
where value is equal to a number in the completed script and I want to import that number into the new script, and that line of code in the old script is: "value=500"
I would not recommend your approach for extracting a variable. You should instead have a look at actual data exchange formats e.g. json or xml.
These are designed to hold and make accessible key-value pairs for programs while being (to some extend) human readable.
Parsers for these formats and many more are available.
Whenever you import any python module or package and you use some function or value from that module it is not run all the script at once.
You can do it like that.
new script: - new.py
old script:- old.py
if it's in same directory..
from old import value
a = value
I would suggest moving the part you want to import to a separate module and importing it to all modules it's used in
my_var.py
text = "Hello"
test.py
from my_var import text
def hello_friend(friend_name)
print(text + " " + friend_name)
main.py
from my_var import text
print(text)
You may also set an environmental variable and check it's value in the module you are importing
test.py
import os
if os.environ['only_new_str'] != str(True):
print("new_str is not calculated yet")
new_str = "Hello world"
if os.environ['only_new_str'] != str(True):
print("new_str calculated")
main.py
import os
os.environ['only_new_str'] = str(True)
import test
print(test.new_str)
if you import with the command
from package import value
the value will come to your new code as being part of it
E.g
Source.py
value = 500
other = 400
Destiny.py
from Source import value
print (value)
>>500
Destiny.py
from Source import value
print (other)
>>NameError: name 'other' is not defined
From Perspective Of Pentester/Red Team in Attack
Okay so lets say we are trying our best to avoid detection or to avoid Blue Team from realizing that the script imports the module 'x'.
We implement a fail-safe in our code that checks whether condition a is true. If this is not our target, we want the script to act in a way that won't draw attention.
From my understanding, Blue Team can use process analysis (is that the right word?) to find out what the python script actually does when ran.
Assuming Blue Team is not looking at the actual python script but instead, looking at the calls the python script makes, would it be possible to only import a module when condition a is true. This would then lower the detection threshold.
However, I came across python documentation that recommends to keep all imports at the beginning of a script. With this, we wouldn't be able to implement IF statements to choose whether we should import something or not.
Pseudocode (Python)
import sys
# ...other functions
def check_user():
# check user against target fingerprint
if a is True:
import x
TLDR: Can I use IF/THEN statements for importing modules? Can I import a module later on in a python script?
Security-Related Question: What is a good program to use to analyze python scripts and their calls / actions without analyzing the actual code?
You can import modules conditionally in Python.
Example :
def check():
if sys.version_info[0] == 2:
from itertools import izip
else:
izip = zip
a=[1,2,3]
b=[4,5,6]
print(izip)
for c in izip(a,b):
print(c)
Here based on Python version izip is imported conditionally
You can do something like below:
import sys
if sys.version_info > (2, 7):
import simplejson as json
else:
import json
I have written a script for XBMC which optionally downloads a dll and then imports a module that depends on that dll if the download was successful.
However, placing the import inside a function generates a Python syntax warning.
Simplified example:
1 def importIfPresent():
2 if chkFunction() is True:
3 from myOptionModule import *
Line 3 generates the warning, but doesn't stop the script. I can't place this code at the start outside of a function because I need to generate dialog boxes to prompt the download and then hash the file once it is downloaded to check success. I also call this same code at startup in order to check if the user has already downloaded the dll.
Is there a different/better way to do this without generating the syntax warning? Or should I just ignore the warning and leave it as is?
Thank you! Using the useful responses below, I now have:
import importlib
myOptionalModule = None
def importIfPresent():
if chkFunction is True:
try:
myOptionalModule = importlib.import_module('modulex')
except ImportError:
myOptionalModule = None
...
importIfPresent()
...
def laterFunction():
if myOptionalModule != None:
myParam = 'something expected'
myClass = getattr(myOptionalModule, 'importClassName')
myFunction = getattr(myClass, 'functionName')
result = myFunction(myClass(), myParam)
else:
callAlternativeMethod()
I am posting this back mainly to share with other beginners like myself the way I learned through the discussion to use the functionality of a module imported this way instead of the standard import statement. I'm sure that there are more elegant ways of doing this that the experts will share as well...
You're not getting the warning for doing an import inside a function, you're getting the warning for using from <module> import * inside a function. Doing a In Python3, this actually becomes a SyntaxError, not a SyntaxWarning. See this answer for why wildcard imports like this in general, and expecially inside functions are discouraged.
Also, this code isn't doing what you think it does. When you do an import inside a function, the import only takes affect inside the function. You're not importing that module into the global namespace of the file, which I believe is what you're really trying to do.
As suggested in another answer importlib can help you here:
try:
import myOptionModule as opt
except ImportError:
opt = None
def importIfPresent():
global opt
if chkFunction() is True:
opt = importlib.import_module("myOptionModule")
I beleive you need to use the importlib library to facilitate this.
The code would be at the top of the mod:
import importlib
then replace "from myOptionModule import *" with "module = importlib.import_module(myOptionModule)". You can then import the defs/classes you want or import them all by using getattr(module,NAME(S)TOIMPORT).
See if that works.
Check out chapter 30 and 31 of Learning Python by Lutz for more info.
I am wanting to call different imports based on the value of a variable in python.
Normally I may do this with a switch statement, but alas python has none...
I was thinking about having a list of functions each of which contains a different import, but is there a better way? Is it possible to list imports in a similar way to methods? Or store the module names as strings in a list, then convert them into a form that can be used to import them?
Thanks
If you want to import a module programatically, you can do
module = __import__('module_name')
It seems like a strange situation to find yourself in though.. check your design and proceed with care.
Usually, in Python, you can replace a switch structure by a dictionary. To import a module using a name stored into a string, you can use importlib.import_module(). Here is an example:
from importlib import import_module
modlist = {'case 1': ('package1', 'module1'), 'case 2': ('package2', 'module2')}
myvar = 'case 2'
mypackage, mymodule = modlist[myvar]
import_module(mymodule, mypackage)
Why don't you use if?
if a is "import_module1":
import module1
elif a is "import_module2":
import module2
An example from my own code http://felicitous-desktop.googlecode.com/files/felicitous.py
The script sets a desktop background. Depending whether the desktop is Windows or Gnome, it imports different libraries:
if ( platform.system() == "Windows" ):
set_windows_background(dest)
else:
set_gnome_background(dest)
where
def set_gnome_background(x):
import gconf
client = gconf.client_get_default()
client.set_string ("/desktop/gnome/background/picture_filename",x)
def set_windows_background(x):
import ctypes
SPI_SETDESKWALLPAPER = 20 # According to http://support.microsoft.com/default.aspx?scid=97142
import tempfile
from PIL import Image
image = Image.open(x)
bmppath= os.path.normpath(os.path.expanduser("~/epic.bmp"))
image.save (bmppath, "BMP")
print bmppath
ctypes.windll.user32.SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, bmppath , 0)
If you have a collection of methods in a file, is there a way to include those files in another file, but call them without any prefix (i.e. file prefix)?
So if I have:
[Math.py]
def Calculate ( num )
How do I call it like this:
[Tool.py]
using Math.py
for i in range ( 5 ) :
Calculate ( i )
You will need to import the other file as a module like this:
import Math
If you don't want to prefix your Calculate function with the module name then do this:
from Math import Calculate
If you want to import all members of a module then do this:
from Math import *
Edit: Here is a good chapter from Dive Into Python that goes a bit more in depth on this topic.
Just write the "include" command :
import os
def include(filename):
if os.path.exists(filename):
execfile(filename)
include('myfile.py')
#Deleet :
#bfieck remark is correct, for python 2 and 3 compatibility, you need either :
Python 2 and 3: alternative 1
from past.builtins import execfile
execfile('myfile.py')
Python 2 and 3: alternative 2
exec(compile(open('myfile.py').read()))
If you use:
import Math
then that will allow you to use Math's functions, but you must do Math.Calculate, so that is obviously what you don't want.
If you want to import a module's functions without having to prefix them, you must explicitly name them, like:
from Math import Calculate, Add, Subtract
Now, you can reference Calculate, Add, and Subtract just by their names. If you wanted to import ALL functions from Math, do:
from Math import *
However, you should be very careful when doing this with modules whose contents you are unsure of. If you import two modules who contain definitions for the same function name, one function will overwrite the other, with you none the wiser.
I've found the python inspect module to be very useful
For example with teststuff.py
import inspect
def dostuff():
return __name__
DOSTUFF_SOURCE = inspect.getsource(dostuff)
if __name__ == "__main__":
dostuff()
And from the another script or the python console
import teststuff
exec(DOSTUFF_SOURCE)
dostuff()
And now dostuff should be in the local scope and dostuff() will return the console or scripts _name_ whereas executing test.dostuff() will return the python modules name.
It's easy and simple:
you can just do this:
def run_file(path):
return exec(open(path).read());
run_file("myfile.py");
I would like to emphasize an answer that was in the comments that is working well for me. As mikey has said, this will work if you want to have variables in the included file in scope in the caller of 'include', just insert it as normal python. It works like an include statement in PHP. Works in Python 3.8.5.
Alternative #1
import textwrap
from pathlib import Path
exec(textwrap.dedent(Path('myfile.py').read_text()))
Alternative #2
with open('myfile.py') as f: exec(f.read())
I prefer Alternative #2 and have been using it in my website development.