Win10下Bash中运行调用SQL的Python脚本及pid_info.py报错求助
Hey there! Let's walk through the most common tweaks you'll need to get python pid_info.py 12345 working smoothly in Windows 10's Bash environment:
Double-check your Python command alias
In many Windows Bash setups,pythonpoints to Python 2 by default, but your script is likely written for Python 3. Try replacing the command withpython3 pid_info.py 12345first. Also, make sure your script starts with the correct shebang line at the top:#!/usr/bin/env python3to ensure the right interpreter is used.Install SQL-related dependencies in Bash
Your Windows Python environment's packages don't carry over to the Bash subsystem. If your script uses libraries likepsycopg2(PostgreSQL),pyodbc(SQL Server), ormysql-connector-python(MySQL), install them directly in Bash with the correct pip command. For example:# For PostgreSQL pip3 install psycopg2-binary # For MySQL pip3 install mysql-connector-python # For SQL Server pip3 install pyodbcFix SQL database connection settings
If your script connects to a Windows-local database,localhostwon't work in Bash (it refers to the Linux subsystem itself). Replacelocalhostwith your Windows machine's actual IP address (you can find this viaipconfigin Command Prompt). Also:- Ensure your database allows remote connections from the Bash subsystem's IP range.
- Double-check that your username, password, database name, and port number are correct in the script's connection string.
Verify script path and permissions
If you're not in the same directory aspid_info.py, eithercdto that folder first or use the full absolute path in the command (e.g.,python3 /home/your_username/scripts/pid_info.py 12345). You can also add execute permissions to the script withchmod +x pid_info.pyso you can run it directly (if you have the shebang line set).Validate command-line parameter handling
Make sure your script properly captures the12345argument. At minimum, it should include:import sys if len(sys.argv) < 2: print("Please provide a PID as an argument") sys.exit(1) pid = int(sys.argv[1]) # Convert to integer if needed for SQL queriesIf you skip converting to the right type, your SQL query might throw a type mismatch error.
Adjust Windows file paths for Bash
If your script references Windows file paths (like config files or CSV inputs), convert them to Bash's Linux-style path format. For example,C:\Users\jhallvid\db_config.txtbecomes/mnt/c/Users/jhallvid/db_config.txt. Bash can't read Windows-style paths directly, which could break your SQL setup if it relies on external files.
内容的提问来源于stack exchange,提问作者jhallvid

