argparse in python3 - cannot add argument with - in name? - python

This is my sample program:
#!/usr/bin/python
import os
import string
import argparse
parser = argparse.ArgumentParser(description="get all versions")
parser.add_argument(test-version)
version = parser.parse_args()
print(version.test-version)
When I run the python script, it throws the error:
AttributeError: 'Namespace' object has no attribute 'test'
If I try the same example with argument "test" instead of "test-version" it works fine.
It is important for me to have the - in my argument name.
How can I fix this issue?
Thanks

The issue is that you can't have a - in a variable name, because it's the subtraction operator. So, in your code, the interpreter is trying to do version.test - version, which doesn't work because version doesn't have a .test attribute and you can't subtract a namespace from something. If you want to use - in the argument, you need to set the dest= parameter in .add_argument().
For example:
import argparse
parser = argparse.ArgumentParser(description="get all versions")
parser.add_argument('--test-version', dest='test_version')
version = parser.parse_args(['--test-version', '1'])
print(version.test_version)
or if you want it as a status flag:
import argparse
parser = argparse.ArgumentParser(description="get all versions")
parser.add_argument('--test-version', action='store_true', dest='test_version')
version = parser.parse_args(['--test-version'])
print(version.test_version)

Try this:
print(getattr(version, 'test-version'))

Related

Error Importing a variable from one Python script to another

I have two Python (3.8) scripts located in the same folder.
The first lookup.py is simply:
#! /usr/bin/env python3
import os
from getimp import session0
print (session0)
The second script getimp.py identifies a cookie and sets it as a variable which is imported into the first script. I have omitted some of the code here, but hopefully have the critical parts.
#! /usr/bin/env python3
import os
import json
import base64
import sqlite3
import shutil
from datetime import datetime, timedelta
import win32crypt # pip install pypiwin32
from Crypto.Cipher import AES # pip install pycryptodome
def get_chrome_datetime(chromedate):
"""Return a `datetime.datetime` object from a chrome format datetime
....
....
# you can also search by domain, e.g thepythoncode.com
cursor.execute("""
SELECT host_key, name, value, creation_utc, last_access_utc, expires_utc, encrypted_value
FROM cookies
WHERE name like '%user_id%'""")
# get the AES key
key = get_encryption_key()
for host_key, name, value, creation_utc, last_access_utc, expires_utc, encrypted_value in cursor.fetchall():
if not value:
decrypted_value = decrypt_data(encrypted_value, key)
else:
# already decrypted
decrypted_value = value
print(f"""
{decrypted_value}
===============================================================""")
session0 = decrypted_value
if __name__ == "__main__":
main()
If I run getimp.py on its own it generates the correct result but when I run lookup.py I get an error:
File "lookup", line 4, in <module>
from getimp import session0
ImportError: cannot import name 'session0' from 'getimp' (D:\Documents\ptest\getimp.py)
Am I losing the variable once the script getimp.py finishes?
Your problem is that the variablesession0 is defined inside the scope of get_chrome_datetime and therefore can not be addressed from import.
Try importing the function and create the variable inside the scope of the active script.
Inside 'get_chrome_datetime' change session0=decrypted_value into return decrypted_value
and in lookup.py :
import os
from getimp import get_chrome_datetime
print (get_chrome_datetime(argument))
Your problem is that session0 is defined inside the function.
I would suggest the following
session0 = None
def get_chrome_datetime(chromedate):
global session0
... (your code here)
Also you should call the function outside of if __name__ == '__main__' because when you're importing a module, the __name__ wouldn't be "__main__"

Why I cannot import function from another py file in current directory?

I cannot import functions from another py file.
How can I import function from another py file in the same directory?
Two py files are in the same directory.
The Python version is 3.7.
OS is Windows 10.
Please help, thank you very much.
db.py
from parser import parser # No name 'parser' in module 'parser'
def _db():
'''
Function: Get sql from GUI, and pass it to paser
'''
print('__Start DBMS__')
# TODO
print('__End DBMS__')
pass
if __name__ == "__main__":
_db()
parser()
parser.py
def parser(_sql=None):
'''
Funtion: Get sql string, and parse it and call cressponding functions
'''
print('__Start Parsing__')
# TODO
print('__End Parsing__')
pass
Traceback (most recent call last):
File "db.py", line 1, in
from parser import parser
ImportError: cannot import name 'parser' from 'parser' (unknown location)
Change the file name parser.py to something else like parser1.py and,
from parser1 import parser
should work as expected.
Because the compiler thinks you are referring to the python parser library
because python have built-in moudle named parser, your moudle conflict with it, the solution has two:
1. change your module name.
2. use absolute path, but first, you should add your project directory into PATH, if you use PyCharm, it can help you do it defaultly.
if your project struction like this,
...other directory...
--top_layer
--second_layer
--parser.py
you can import like this
from top_layer.parser import parser
excuse my english is poor!

Extended interpolation not working in configparser

I tried to use configparser module from standard library in python 3.6 or python 3.5.1
My ini file looks like this:
[common]
domain = http://some_domain_name:8888
about = about/
loginPath = /accounts/login/?next=/home
fileBrowserLink = /filebrowser
partNewDirName = some_dir
[HUE_310]
partNewFilePath = ${common:domain}
My "main" program looks like this:
from configparser import ConfigParser
parser = ConfigParser()
parser.read('configfile.ini')
lll = parser.get('HUE_310', 'partNewFilePath')
print(lll)
Instead http://some_domain_name:8888 I got ${common:domain}
I use Pycharm Community as my IDE. I use virtualenv.
I have no idea what is wrong with my code...
If you want extended interpolation, you have to create an instance of the configparser.ExtendedInterpolation class, by calling it, and then using that with the interpolation= keyword argument when you create the ConfigParser instance as shown below:
from configparser import ConfigParser, ExtendedInterpolation
parser = ConfigParser(interpolation=ExtendedInterpolation())
parser.read('configfile.ini')
lll = parser.get('HUE_310', 'partNewFilePath')
print(lll) # -> http://some_domain_name:8888

NameError: name 'argv' is not defined

I am trying to make a Google API call and am getting an error with the beginning of the code found here:
import os
import argparse
import sys
from apiclient import sample_tools
from oauth2client import client
# Declare command-line flags.
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument(
'profile_id', type=int,
help='The ID of the profile to look up campaigns for')
# Authenticate and construct service.
service, flags = sample_tools.init(
argv[1:], 'dfareporting', 'v2.1', __doc__, os.path.abspath(os.path.dirname("__file__")), parents=[argparser],
scope=['https://www.googleapis.com/auth/dfareporting',
'https://www.googleapis.com/auth/dfatrafficking'])
if __name__ == '__main__':
main(sys.argv)
However, the sample_tools.init function is not returning the service and flags object. I think I have isolated it to the argv argument a
NameError: name 'argv' is not defined
Any help would be much appreciated!!!
You are missing sys:
sys.argv[1:]
You either need to from sys import argv and use argv everywhere or import sys as you have and use sys.argv. I also don't see a main function anywhere so main(sys.argv) is also going to cause a NameError

import file by url route python

Im trying to import files on Flask app in base of url route. I started to coding python few days ago so i havent idea if i doing it well. I write this on :
#app.route('/<file>')
def call(file):
__import__('controller.'+file)
hello = Example('Hello world')
return hello.msg
And i have other file called example.py into a controller folder that contains this:
class Example:
def __init__(self, msg):
self.msg = msg
So i start from terminal the app and i try to enter to localhost:5000/example.
Im trying to show in screen Hello world but give me the next error:
NameError: global name 'Example' is not defined
Thanks for all!
__import__ returns the newly imported module; names from that module are not added to your globals, so you need to get the Example class as an attribute from the returned module:
module = __import__('controller.'+file)
hello = module.Example('Hello world')
__import__ is rather low-level, you probably want to use importlib.import_module() instead:
import importlib
module = importlib.import_module('controller.'+file)
hello = module.Example('Hello world')
If you need to dynamically get the classname too, use getattr():
class_name = 'Example'
hello_class = getattr(module, class_name)
hello = hello_class('Hello world')
The Werkzeug package (used by Flask) offers a helpful functions here: werkzeug.utils.import_string() imports an object dynamically:
from werkzeug.utils import import_string
object_name = 'controller.{}:Example'.format(file)
hello_class = import_string(object_name)
This encapsulates the above process.
You'll need to be extremely careful with accepting names from web requests and using those as module names. Please do sanitise the file argument and only allow alphanumerics to prevent relative imports from being used.
You could use the werkzeug.utils.find_modules() function to limit the possible values for file here:
from werkzeug.utils import find_modules, import_string
module_name = 'controller.{}'.format(file)
if module_name not in set(find_modules('controller')):
abort(404) # no such module in the controller package
hello_class = import_string(module_name + ':Example')
I think you might not add the directory to the file, add the following code into the previous python program
# Add another directory
import sys
sys.path.insert(0, '/your_directory')
from Example import Example
There are two ways for you to do imports in Python:
import example
e = example.Example('hello world')
or
from example import Example
e = Example('hello world')

Categories

Resources