pass command-line arguments to runpy

2024/9/29 1:30:28

I have two files, one which has a side effect I care about that occurs within the if __name__ == "__main__" guard:

# a.py
d = {}
if __name__ == "__main__":d['arg'] = 'hello'

The second file imports the first (using runpy) and prints the dictionary:

# b.py
import runpy
m = runpy.run_module('a', run_name='__main__')
print(m['d'])  # {'arg': 'hello'}

So far this works. But now I want to change the first file to accept a command line argument:

import sys
d = {}
if __name__ == "__main__":d['arg'] = process(sys.argv[1])

The problem is that process() is written by someone else and outside of my control, but I still want to get the updated dictionary d after it has been "processed".

How can I mock sys.argv before calling runpy, or otherwise provide that value to a.py?

Answer

Could it be this straightforward? I found this solution almost by accident.

$ python3 b.py foo
{'arg': 'foo'}

It seems that sys.argv[1] is passed in to a even when b.py is called from the command line.

edit

here is an example session from my shell:

me@desktop$ cat a.py b.py
import sys
d = {}
filename = sys.argv[1]
if __name__ == "__main__":d['result'] = filename + ' world'# usage:
# python3 b.py filename
# 'filename' is passed in to the a module
import runpy
aa = runpy.run_module('a', run_name='__main__')
print(aa['d'])  # {}me@desktop$ python3 b.py hello
{'result': 'hello world'}
https://en.xdnf.cn/q/71266.html

Related Q&A

Altering my python path: helloworld.py returns command not found—

Massive apologies for this embarrassing question—Im using my MacBook Pro, running snow leopard, and using Python 2.7.1. Trying to run my first script and all the first pages of all my tutorials are la…

ImportError: cannot import name force_text

I have installed Python 2.7 and Django 1.4 in my CentOS machine and installed all dependencies for my existing project. When I run python manage.py runserver, I am getting the following traceback in my…

How can I select the pixels that fall within a contour in an image represented by a numpy array?

VI have a set of contour points drawn on an image which is stored as a 2D numpy array. The contours are represented by 2 numpy arrays of float values for x and y coordinates each. These coordinates are…

Get the value of specific JSON element in Python

Im new to Python and JSON, so Im sorry if I sound clueless. Im getting the following result from the Google Translate API and want to parse out the value of "translatedText":{"data"…

How does setuptools decide which files to keep for sdist/bdist?

Im working on a Python package that uses namespace_packages and find_packages() like so in setup.py:from setuptools import setup, find_packages setup(name="package",version="1.3.3.7"…

How to implement multivariate linear stochastic gradient descent algorithm in tensorflow?

I started with simple implementation of single variable linear gradient descent but dont know to extend it to multivariate stochastic gradient descent algorithm ?Single variable linear regression impo…

How to do os.execv() in Python in Windows without detaching from the console?

Im using Python 2.6 on Windows 7. I have Windows .cmd file which invokes Python to run the CherryPy Web server (version 3.1.2). I start this .cmd file by executing it at the prompt in a Windows CMD she…

Django queryset permissions

I am building a quite complex Django application to be used on top of and email scanning service. The Django application is written using Python 3.5+This application primarily uses Django Rest Framewor…

How to extract certain parts of a web page in Python

Target web page: http://www.immi.gov.au/skilled/general-skilled-migration/estimated-allocation-times.htmThe section I want to extract:<tr><td>Skilled &ndash; Independent (Residence) sub…

Accessing axis or figure in python ggplot

python ggplot is great, but still new, and I find the need to fallback on traditional matplotlib techniques to modify my plots. But Im not sure how to either pass an axis instance to ggplot, or get one…