You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python:使用全局变量替代函数参数的脚本修改方案

Using Global Variables Instead of Function Parameters in Python

Got it, so you want to swap out the function parameter in your script with a global variable initialized from the command line. Here's how to adjust your code to make that work smoothly:

First, define your global variables right at the start of the script, using sys.argv to grab the input directory from the command line. We’ll also calculate the output directory here instead of inside the function:

import sys

# Define global variables upfront
inDir = sys.argv[1]
# Calculate outDir based on inDir's structure
if inDir.endswith("/"):
    outDir = "/".join(inDir.split("/")[:-2]) + "/" + inDir.split("/")[-2] + "_cv"
else:
    outDir = "/".join(inDir.split("/")[:-1]) + "/" + inDir.split("/")[-1] + "_cv"

def check_outDir():
    # Now we use the global inDir instead of a parameter
    # No need to pass indir anymore—we can access the global variable directly
    if inDir.endswith("/"):
        # You can reuse the precomputed global outDir or add your existing logic here
        if not os.path.exists(outDir):
            os.makedirs(outDir)
            print(f"Created output directory: {outDir}")
        else:
            print(f"Output directory already exists: {outDir}")
    # Rest of your function logic goes here

# Call the function without passing any parameters
check_outDir()

Key Changes Explained:

  • Global Variable Setup: We moved the input/output directory logic to the top of the script, making inDir and outDir available to all functions in the script.
  • Function Parameter Removal: The check_outDir function no longer takes an indir parameter. It directly uses the global inDir variable we defined earlier.
  • Global Access: Since we’re only reading the global variables (not modifying them inside the function), we don’t need the global keyword here. If you ever need to modify the global variable within the function, add global inDir at the start of the function to tell Python you’re referring to the global instance, not a local one.

A quick heads-up: While globals work well for simple scripts like this, overusing them can make code harder to test and maintain. But for your specific use case, this is a clean, straightforward solution.

内容的提问来源于stack exchange,提问作者F.Lira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 02:32:33