```bash
my_test()
{
python <<EOF

import sys

print(f'{sys.argv=}')

EOF
}
my_test 42
```
```
sys.argv['']
```

How to make this Python code output `sys.argv['42']`?
Jul 1, 10:50am

The issue is that in your Bash function, the python <<EOF ... EOF heredoc does not pass the command-line arguments (42) to the Python script. The sys.argv list in Python only contains the script name (or an empty string if run interactively) because no arguments are being passed.

To make sys.argv contain ['', '42'] (or similar), you need to explicitly pass the arguments to the Python command. Here’s how you can fix it:

Solution

Use the -c flag to pass the script as a string and include the arguments:

bash
my_test()
{
    python -c "
import sys
print(f'{sys.argv=}')
" "$@"
}
my_test 42

Explanation:

  • "$@" expands to all positional parameters as separate words, so 42 is passed as an argument to the Python script.
  • The -c flag allows you to pass the script directly as a string.

Output:

python
sys.argv=['-c', '42']

If you want sys.argv to start with an empty string (as in your example), you can adjust the script like this:

bash
my_test()
{
    python -c "
import sys
sys.argv = [''] + sys.argv[1:]
print(f'{sys.argv=}')
" "$@"
}
my_test 42

Output:

python
sys.argv=['', '42']
Jul 1, 10:50am

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Vibe can make mistakes. Check answers. Learn more